76
http://www.danga.com/words/ LiveJournal: Behind The Scenes Scaling Storytime April 2007 Brad Fitzpatrick [email protected] danga.com / livejournal.com / sixapart.com This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/1.0/ or send a letter to Creative Commons, 559 Nathan Abbott Way, Stanford, California 94305, USA.

LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

  • Upload
    others

  • View
    2

  • Download
    0

Embed Size (px)

Citation preview

Page 1: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

LiveJournal Behind The ScenesScaling Storytime

April 2007

Brad Fitzpatrickbraddangacom

dangacom livejournalcom sixapartcom

This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike License To view a copy of this license visit httpcreativecommonsorglicensesby-nc-sa10 or send a letter to

Creative Commons 559 Nathan Abbott Way Stanford California 94305 USA

httpwwwdangacomwords

LiveJournal Overview

college hobby project Apr 1999 4-in-1

ndash bloggingndash forumsndash social-networking (ldquofriendsrdquo)ndash aggregator ldquofriends pagerdquo +

RSSAtom 10M+ accounts Open Source

ndash serverndash infrastructurendash original clientsndash

大学時代のお遊びプロジェクト 4-in-1

ndash ブログndash フォーラムndash SNS (友達 )ndash RSSAtomアグレゲーター

ユーザーは1000万人強 もちろんオープンソースで作成

ndash serverndash infrastructurendash original clientsndash

httpwwwdangacomwords

memcachedndash distributed caching

MogileFSndash distributed filesystem

Perlbalndash HTTP load balancer amp web server

gearmanndash LBHAcoalescing low-latency

function call ldquorouterrdquo TheSchwartz

ndash reliable async job dispatch system djabberd

ndash the mod_perlqpsmtpd of XMPPJabber servers

OpenID

Stuff weve built

memcachedndash 分散型キャッシングフレームワーク

MogileFSndash 分散型ファイルシステム

Perlbalndash HTTPロードバランサーWeb サーバー

gearmanndash 待ち時間の少ないリモートファンクションコール ldquoルータrdquo

TheSchwartzndash 非同期ジョブ管理システム

djabberdndash the mod_perlqpsmtpd of

XMPPJabber servers

httpwwwdangacomwords

LiveJournal Backend Today今のLiveJournal のおおまかな構成

(Roughly)

User DB Cluster 1uc1a uc1b

User DB Cluster 2uc2a uc2b

User DB Cluster 3uc3a uc3b

User DB Cluster NucNa ucNb

Job Queues (xN)jqNa jqNb

Memcached

mc4

mc3

mc2

mc12

mc1

mod_perl

web4

web3

web2

web50

web1

BIG-IP

bigip2bigip1 perlbal (httpdproxy)

proxy4

proxy3

proxy2

proxy5

proxy1

Global Database

slave1

master_a master_b

slave2 slave5

MogileFS Database

mog_a mog_b

Mogile Trackerstracker2tracker1

Mogile Storage Nodes

sto2sto8

sto1

net

djabberddjabberddjabberd

gearmandgearmand1gearmandN

ldquoworkersrdquogearwrkNtheschwkN

slave1 slaveN

httpwwwdangacomwords

The plan

Refer to previous presentations for more detail

Questions anytime Part I

ndash quick scaling historyndash スケーラビリティとの闘いその歴史

Part IIndash explain all our softwarendash explain all the parts

httpwwwdangacomwords

Part IQuick Scaling Historyスケーラビリティとの闘いその歴史

httpwwwdangacomwords

Quick Scaling History

1 server to hundreds 1 台のサーバが数百台に増えるまで

httpwwwdangacomwords

One Serverサーバ1 台

Simple 構造は単純

httpwwwdangacomwords

Two Serversサーバ2 台

httpwwwdangacomwords

Two Servers - Problemsサーバを2 台にしたときの問題

Two single points of failure どっちが落ちても全部が落ちる No hot or cold spares 予備の機械がない Site gets slow again ユーザが増えるとまた遅くなる

ndash CPU-bound on web nodendash webサーバがCPUを食うndash need more web nodesndash もっとwebサーバが必要

httpwwwdangacomwords

Four Serversサーバ4 台

3 webs 1 db web サーバ3 台データベース1 台 Now we need to load-balance 負荷分散をしよう

httpwwwdangacomwords

Four Servers - Problemsサーバを4 台にしたときの問題

Now IO bound 今度は IO に時間がかかる

ndash how to use another databasendash データベースを増やそう

httpwwwdangacomwords

Five Servers サーバ5 台introducing MySQL replication

MySQLのレプリケーションを使ってみよう

We buy a new DB MySQL replication Writes to DB (master) Reads from both

新しいDB サーバを買う MySQL のレプリケーション データの書き込みはマスタDB1 台へ

データの読み込みは2 台から

httpwwwdangacomwords

More Serversサーバの数が増えていく

Chaosわけがわからない

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 2: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

LiveJournal Overview

college hobby project Apr 1999 4-in-1

ndash bloggingndash forumsndash social-networking (ldquofriendsrdquo)ndash aggregator ldquofriends pagerdquo +

RSSAtom 10M+ accounts Open Source

ndash serverndash infrastructurendash original clientsndash

大学時代のお遊びプロジェクト 4-in-1

ndash ブログndash フォーラムndash SNS (友達 )ndash RSSAtomアグレゲーター

ユーザーは1000万人強 もちろんオープンソースで作成

ndash serverndash infrastructurendash original clientsndash

httpwwwdangacomwords

memcachedndash distributed caching

MogileFSndash distributed filesystem

Perlbalndash HTTP load balancer amp web server

gearmanndash LBHAcoalescing low-latency

function call ldquorouterrdquo TheSchwartz

ndash reliable async job dispatch system djabberd

ndash the mod_perlqpsmtpd of XMPPJabber servers

OpenID

Stuff weve built

memcachedndash 分散型キャッシングフレームワーク

MogileFSndash 分散型ファイルシステム

Perlbalndash HTTPロードバランサーWeb サーバー

gearmanndash 待ち時間の少ないリモートファンクションコール ldquoルータrdquo

TheSchwartzndash 非同期ジョブ管理システム

djabberdndash the mod_perlqpsmtpd of

XMPPJabber servers

httpwwwdangacomwords

LiveJournal Backend Today今のLiveJournal のおおまかな構成

(Roughly)

User DB Cluster 1uc1a uc1b

User DB Cluster 2uc2a uc2b

User DB Cluster 3uc3a uc3b

User DB Cluster NucNa ucNb

Job Queues (xN)jqNa jqNb

Memcached

mc4

mc3

mc2

mc12

mc1

mod_perl

web4

web3

web2

web50

web1

BIG-IP

bigip2bigip1 perlbal (httpdproxy)

proxy4

proxy3

proxy2

proxy5

proxy1

Global Database

slave1

master_a master_b

slave2 slave5

MogileFS Database

mog_a mog_b

Mogile Trackerstracker2tracker1

Mogile Storage Nodes

sto2sto8

sto1

net

djabberddjabberddjabberd

gearmandgearmand1gearmandN

ldquoworkersrdquogearwrkNtheschwkN

slave1 slaveN

httpwwwdangacomwords

The plan

Refer to previous presentations for more detail

Questions anytime Part I

ndash quick scaling historyndash スケーラビリティとの闘いその歴史

Part IIndash explain all our softwarendash explain all the parts

httpwwwdangacomwords

Part IQuick Scaling Historyスケーラビリティとの闘いその歴史

httpwwwdangacomwords

Quick Scaling History

1 server to hundreds 1 台のサーバが数百台に増えるまで

httpwwwdangacomwords

One Serverサーバ1 台

Simple 構造は単純

httpwwwdangacomwords

Two Serversサーバ2 台

httpwwwdangacomwords

Two Servers - Problemsサーバを2 台にしたときの問題

Two single points of failure どっちが落ちても全部が落ちる No hot or cold spares 予備の機械がない Site gets slow again ユーザが増えるとまた遅くなる

ndash CPU-bound on web nodendash webサーバがCPUを食うndash need more web nodesndash もっとwebサーバが必要

httpwwwdangacomwords

Four Serversサーバ4 台

3 webs 1 db web サーバ3 台データベース1 台 Now we need to load-balance 負荷分散をしよう

httpwwwdangacomwords

Four Servers - Problemsサーバを4 台にしたときの問題

Now IO bound 今度は IO に時間がかかる

ndash how to use another databasendash データベースを増やそう

httpwwwdangacomwords

Five Servers サーバ5 台introducing MySQL replication

MySQLのレプリケーションを使ってみよう

We buy a new DB MySQL replication Writes to DB (master) Reads from both

新しいDB サーバを買う MySQL のレプリケーション データの書き込みはマスタDB1 台へ

データの読み込みは2 台から

httpwwwdangacomwords

More Serversサーバの数が増えていく

Chaosわけがわからない

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 3: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

memcachedndash distributed caching

MogileFSndash distributed filesystem

Perlbalndash HTTP load balancer amp web server

gearmanndash LBHAcoalescing low-latency

function call ldquorouterrdquo TheSchwartz

ndash reliable async job dispatch system djabberd

ndash the mod_perlqpsmtpd of XMPPJabber servers

OpenID

Stuff weve built

memcachedndash 分散型キャッシングフレームワーク

MogileFSndash 分散型ファイルシステム

Perlbalndash HTTPロードバランサーWeb サーバー

gearmanndash 待ち時間の少ないリモートファンクションコール ldquoルータrdquo

TheSchwartzndash 非同期ジョブ管理システム

djabberdndash the mod_perlqpsmtpd of

XMPPJabber servers

httpwwwdangacomwords

LiveJournal Backend Today今のLiveJournal のおおまかな構成

(Roughly)

User DB Cluster 1uc1a uc1b

User DB Cluster 2uc2a uc2b

User DB Cluster 3uc3a uc3b

User DB Cluster NucNa ucNb

Job Queues (xN)jqNa jqNb

Memcached

mc4

mc3

mc2

mc12

mc1

mod_perl

web4

web3

web2

web50

web1

BIG-IP

bigip2bigip1 perlbal (httpdproxy)

proxy4

proxy3

proxy2

proxy5

proxy1

Global Database

slave1

master_a master_b

slave2 slave5

MogileFS Database

mog_a mog_b

Mogile Trackerstracker2tracker1

Mogile Storage Nodes

sto2sto8

sto1

net

djabberddjabberddjabberd

gearmandgearmand1gearmandN

ldquoworkersrdquogearwrkNtheschwkN

slave1 slaveN

httpwwwdangacomwords

The plan

Refer to previous presentations for more detail

Questions anytime Part I

ndash quick scaling historyndash スケーラビリティとの闘いその歴史

Part IIndash explain all our softwarendash explain all the parts

httpwwwdangacomwords

Part IQuick Scaling Historyスケーラビリティとの闘いその歴史

httpwwwdangacomwords

Quick Scaling History

1 server to hundreds 1 台のサーバが数百台に増えるまで

httpwwwdangacomwords

One Serverサーバ1 台

Simple 構造は単純

httpwwwdangacomwords

Two Serversサーバ2 台

httpwwwdangacomwords

Two Servers - Problemsサーバを2 台にしたときの問題

Two single points of failure どっちが落ちても全部が落ちる No hot or cold spares 予備の機械がない Site gets slow again ユーザが増えるとまた遅くなる

ndash CPU-bound on web nodendash webサーバがCPUを食うndash need more web nodesndash もっとwebサーバが必要

httpwwwdangacomwords

Four Serversサーバ4 台

3 webs 1 db web サーバ3 台データベース1 台 Now we need to load-balance 負荷分散をしよう

httpwwwdangacomwords

Four Servers - Problemsサーバを4 台にしたときの問題

Now IO bound 今度は IO に時間がかかる

ndash how to use another databasendash データベースを増やそう

httpwwwdangacomwords

Five Servers サーバ5 台introducing MySQL replication

MySQLのレプリケーションを使ってみよう

We buy a new DB MySQL replication Writes to DB (master) Reads from both

新しいDB サーバを買う MySQL のレプリケーション データの書き込みはマスタDB1 台へ

データの読み込みは2 台から

httpwwwdangacomwords

More Serversサーバの数が増えていく

Chaosわけがわからない

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 4: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

LiveJournal Backend Today今のLiveJournal のおおまかな構成

(Roughly)

User DB Cluster 1uc1a uc1b

User DB Cluster 2uc2a uc2b

User DB Cluster 3uc3a uc3b

User DB Cluster NucNa ucNb

Job Queues (xN)jqNa jqNb

Memcached

mc4

mc3

mc2

mc12

mc1

mod_perl

web4

web3

web2

web50

web1

BIG-IP

bigip2bigip1 perlbal (httpdproxy)

proxy4

proxy3

proxy2

proxy5

proxy1

Global Database

slave1

master_a master_b

slave2 slave5

MogileFS Database

mog_a mog_b

Mogile Trackerstracker2tracker1

Mogile Storage Nodes

sto2sto8

sto1

net

djabberddjabberddjabberd

gearmandgearmand1gearmandN

ldquoworkersrdquogearwrkNtheschwkN

slave1 slaveN

httpwwwdangacomwords

The plan

Refer to previous presentations for more detail

Questions anytime Part I

ndash quick scaling historyndash スケーラビリティとの闘いその歴史

Part IIndash explain all our softwarendash explain all the parts

httpwwwdangacomwords

Part IQuick Scaling Historyスケーラビリティとの闘いその歴史

httpwwwdangacomwords

Quick Scaling History

1 server to hundreds 1 台のサーバが数百台に増えるまで

httpwwwdangacomwords

One Serverサーバ1 台

Simple 構造は単純

httpwwwdangacomwords

Two Serversサーバ2 台

httpwwwdangacomwords

Two Servers - Problemsサーバを2 台にしたときの問題

Two single points of failure どっちが落ちても全部が落ちる No hot or cold spares 予備の機械がない Site gets slow again ユーザが増えるとまた遅くなる

ndash CPU-bound on web nodendash webサーバがCPUを食うndash need more web nodesndash もっとwebサーバが必要

httpwwwdangacomwords

Four Serversサーバ4 台

3 webs 1 db web サーバ3 台データベース1 台 Now we need to load-balance 負荷分散をしよう

httpwwwdangacomwords

Four Servers - Problemsサーバを4 台にしたときの問題

Now IO bound 今度は IO に時間がかかる

ndash how to use another databasendash データベースを増やそう

httpwwwdangacomwords

Five Servers サーバ5 台introducing MySQL replication

MySQLのレプリケーションを使ってみよう

We buy a new DB MySQL replication Writes to DB (master) Reads from both

新しいDB サーバを買う MySQL のレプリケーション データの書き込みはマスタDB1 台へ

データの読み込みは2 台から

httpwwwdangacomwords

More Serversサーバの数が増えていく

Chaosわけがわからない

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 5: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

The plan

Refer to previous presentations for more detail

Questions anytime Part I

ndash quick scaling historyndash スケーラビリティとの闘いその歴史

Part IIndash explain all our softwarendash explain all the parts

httpwwwdangacomwords

Part IQuick Scaling Historyスケーラビリティとの闘いその歴史

httpwwwdangacomwords

Quick Scaling History

1 server to hundreds 1 台のサーバが数百台に増えるまで

httpwwwdangacomwords

One Serverサーバ1 台

Simple 構造は単純

httpwwwdangacomwords

Two Serversサーバ2 台

httpwwwdangacomwords

Two Servers - Problemsサーバを2 台にしたときの問題

Two single points of failure どっちが落ちても全部が落ちる No hot or cold spares 予備の機械がない Site gets slow again ユーザが増えるとまた遅くなる

ndash CPU-bound on web nodendash webサーバがCPUを食うndash need more web nodesndash もっとwebサーバが必要

httpwwwdangacomwords

Four Serversサーバ4 台

3 webs 1 db web サーバ3 台データベース1 台 Now we need to load-balance 負荷分散をしよう

httpwwwdangacomwords

Four Servers - Problemsサーバを4 台にしたときの問題

Now IO bound 今度は IO に時間がかかる

ndash how to use another databasendash データベースを増やそう

httpwwwdangacomwords

Five Servers サーバ5 台introducing MySQL replication

MySQLのレプリケーションを使ってみよう

We buy a new DB MySQL replication Writes to DB (master) Reads from both

新しいDB サーバを買う MySQL のレプリケーション データの書き込みはマスタDB1 台へ

データの読み込みは2 台から

httpwwwdangacomwords

More Serversサーバの数が増えていく

Chaosわけがわからない

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 6: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Part IQuick Scaling Historyスケーラビリティとの闘いその歴史

httpwwwdangacomwords

Quick Scaling History

1 server to hundreds 1 台のサーバが数百台に増えるまで

httpwwwdangacomwords

One Serverサーバ1 台

Simple 構造は単純

httpwwwdangacomwords

Two Serversサーバ2 台

httpwwwdangacomwords

Two Servers - Problemsサーバを2 台にしたときの問題

Two single points of failure どっちが落ちても全部が落ちる No hot or cold spares 予備の機械がない Site gets slow again ユーザが増えるとまた遅くなる

ndash CPU-bound on web nodendash webサーバがCPUを食うndash need more web nodesndash もっとwebサーバが必要

httpwwwdangacomwords

Four Serversサーバ4 台

3 webs 1 db web サーバ3 台データベース1 台 Now we need to load-balance 負荷分散をしよう

httpwwwdangacomwords

Four Servers - Problemsサーバを4 台にしたときの問題

Now IO bound 今度は IO に時間がかかる

ndash how to use another databasendash データベースを増やそう

httpwwwdangacomwords

Five Servers サーバ5 台introducing MySQL replication

MySQLのレプリケーションを使ってみよう

We buy a new DB MySQL replication Writes to DB (master) Reads from both

新しいDB サーバを買う MySQL のレプリケーション データの書き込みはマスタDB1 台へ

データの読み込みは2 台から

httpwwwdangacomwords

More Serversサーバの数が増えていく

Chaosわけがわからない

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 7: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Quick Scaling History

1 server to hundreds 1 台のサーバが数百台に増えるまで

httpwwwdangacomwords

One Serverサーバ1 台

Simple 構造は単純

httpwwwdangacomwords

Two Serversサーバ2 台

httpwwwdangacomwords

Two Servers - Problemsサーバを2 台にしたときの問題

Two single points of failure どっちが落ちても全部が落ちる No hot or cold spares 予備の機械がない Site gets slow again ユーザが増えるとまた遅くなる

ndash CPU-bound on web nodendash webサーバがCPUを食うndash need more web nodesndash もっとwebサーバが必要

httpwwwdangacomwords

Four Serversサーバ4 台

3 webs 1 db web サーバ3 台データベース1 台 Now we need to load-balance 負荷分散をしよう

httpwwwdangacomwords

Four Servers - Problemsサーバを4 台にしたときの問題

Now IO bound 今度は IO に時間がかかる

ndash how to use another databasendash データベースを増やそう

httpwwwdangacomwords

Five Servers サーバ5 台introducing MySQL replication

MySQLのレプリケーションを使ってみよう

We buy a new DB MySQL replication Writes to DB (master) Reads from both

新しいDB サーバを買う MySQL のレプリケーション データの書き込みはマスタDB1 台へ

データの読み込みは2 台から

httpwwwdangacomwords

More Serversサーバの数が増えていく

Chaosわけがわからない

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 8: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

One Serverサーバ1 台

Simple 構造は単純

httpwwwdangacomwords

Two Serversサーバ2 台

httpwwwdangacomwords

Two Servers - Problemsサーバを2 台にしたときの問題

Two single points of failure どっちが落ちても全部が落ちる No hot or cold spares 予備の機械がない Site gets slow again ユーザが増えるとまた遅くなる

ndash CPU-bound on web nodendash webサーバがCPUを食うndash need more web nodesndash もっとwebサーバが必要

httpwwwdangacomwords

Four Serversサーバ4 台

3 webs 1 db web サーバ3 台データベース1 台 Now we need to load-balance 負荷分散をしよう

httpwwwdangacomwords

Four Servers - Problemsサーバを4 台にしたときの問題

Now IO bound 今度は IO に時間がかかる

ndash how to use another databasendash データベースを増やそう

httpwwwdangacomwords

Five Servers サーバ5 台introducing MySQL replication

MySQLのレプリケーションを使ってみよう

We buy a new DB MySQL replication Writes to DB (master) Reads from both

新しいDB サーバを買う MySQL のレプリケーション データの書き込みはマスタDB1 台へ

データの読み込みは2 台から

httpwwwdangacomwords

More Serversサーバの数が増えていく

Chaosわけがわからない

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 9: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Two Serversサーバ2 台

httpwwwdangacomwords

Two Servers - Problemsサーバを2 台にしたときの問題

Two single points of failure どっちが落ちても全部が落ちる No hot or cold spares 予備の機械がない Site gets slow again ユーザが増えるとまた遅くなる

ndash CPU-bound on web nodendash webサーバがCPUを食うndash need more web nodesndash もっとwebサーバが必要

httpwwwdangacomwords

Four Serversサーバ4 台

3 webs 1 db web サーバ3 台データベース1 台 Now we need to load-balance 負荷分散をしよう

httpwwwdangacomwords

Four Servers - Problemsサーバを4 台にしたときの問題

Now IO bound 今度は IO に時間がかかる

ndash how to use another databasendash データベースを増やそう

httpwwwdangacomwords

Five Servers サーバ5 台introducing MySQL replication

MySQLのレプリケーションを使ってみよう

We buy a new DB MySQL replication Writes to DB (master) Reads from both

新しいDB サーバを買う MySQL のレプリケーション データの書き込みはマスタDB1 台へ

データの読み込みは2 台から

httpwwwdangacomwords

More Serversサーバの数が増えていく

Chaosわけがわからない

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 10: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Two Servers - Problemsサーバを2 台にしたときの問題

Two single points of failure どっちが落ちても全部が落ちる No hot or cold spares 予備の機械がない Site gets slow again ユーザが増えるとまた遅くなる

ndash CPU-bound on web nodendash webサーバがCPUを食うndash need more web nodesndash もっとwebサーバが必要

httpwwwdangacomwords

Four Serversサーバ4 台

3 webs 1 db web サーバ3 台データベース1 台 Now we need to load-balance 負荷分散をしよう

httpwwwdangacomwords

Four Servers - Problemsサーバを4 台にしたときの問題

Now IO bound 今度は IO に時間がかかる

ndash how to use another databasendash データベースを増やそう

httpwwwdangacomwords

Five Servers サーバ5 台introducing MySQL replication

MySQLのレプリケーションを使ってみよう

We buy a new DB MySQL replication Writes to DB (master) Reads from both

新しいDB サーバを買う MySQL のレプリケーション データの書き込みはマスタDB1 台へ

データの読み込みは2 台から

httpwwwdangacomwords

More Serversサーバの数が増えていく

Chaosわけがわからない

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 11: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Four Serversサーバ4 台

3 webs 1 db web サーバ3 台データベース1 台 Now we need to load-balance 負荷分散をしよう

httpwwwdangacomwords

Four Servers - Problemsサーバを4 台にしたときの問題

Now IO bound 今度は IO に時間がかかる

ndash how to use another databasendash データベースを増やそう

httpwwwdangacomwords

Five Servers サーバ5 台introducing MySQL replication

MySQLのレプリケーションを使ってみよう

We buy a new DB MySQL replication Writes to DB (master) Reads from both

新しいDB サーバを買う MySQL のレプリケーション データの書き込みはマスタDB1 台へ

データの読み込みは2 台から

httpwwwdangacomwords

More Serversサーバの数が増えていく

Chaosわけがわからない

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 12: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Four Servers - Problemsサーバを4 台にしたときの問題

Now IO bound 今度は IO に時間がかかる

ndash how to use another databasendash データベースを増やそう

httpwwwdangacomwords

Five Servers サーバ5 台introducing MySQL replication

MySQLのレプリケーションを使ってみよう

We buy a new DB MySQL replication Writes to DB (master) Reads from both

新しいDB サーバを買う MySQL のレプリケーション データの書き込みはマスタDB1 台へ

データの読み込みは2 台から

httpwwwdangacomwords

More Serversサーバの数が増えていく

Chaosわけがわからない

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 13: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Five Servers サーバ5 台introducing MySQL replication

MySQLのレプリケーションを使ってみよう

We buy a new DB MySQL replication Writes to DB (master) Reads from both

新しいDB サーバを買う MySQL のレプリケーション データの書き込みはマスタDB1 台へ

データの読み込みは2 台から

httpwwwdangacomwords

More Serversサーバの数が増えていく

Chaosわけがわからない

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 14: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

More Serversサーバの数が増えていく

Chaosわけがわからない

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 15: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Where were at現状

mod_perl

web4

web3

web2

web12

web1

BIG-IP

bigip2bigip1

mod_proxy

proxy3

proxy2

proxy1

Global Database

slave1 slave2 slave6

master

net

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 16: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Problems with Architectureor

ldquoThis dont scalerdquo構造的な問題(スケーラビリティがたりない)

DB master is SPOF Adding slaves doesnt scale

wellndash only spreads reads not writes

200 writess 200 writes

500 readss250 readss

200 writes

250 readss

DBのマスタが落ちるともうだめ スレーブを足してもあまり意味がないndash 読み込みだけ分散書き込みは分散しない

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 17: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Eventually

databases eventual only writing データベースは書き込みでいっぱいっぱい

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

400 writes

3 readss

400writes

3 rs

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 18: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Spreading Writes書き込みの分散

Our database machines already did RAID

We did backups So why put user data

on 6+ slave machines (~12+ disks)ndash overkill redundancyndash wasting time writing

everywhere

DB の機械はRAID 装備 バックアップもとっている ユーザのデータは6 台以上のスレーブにコピーがある

( ディスク12 個以上 )ndash 冗長すぎndash 全部のディスクに書く時間ももったいない

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 19: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Partition your dataデータを分割しよう

Spread your databases out into ldquorolesrdquondash roles that you never need

to join between different users or accept youll have

to join in app Each user assigned to a

cluster number Each cluster has multiple

machinesndash writes self-contained in

cluster (writing to 2-3 machines not 6)

Spread your databases out into ldquorolesrdquondash それぞれが独立したデータを保持

たとえば違うユーザを違うDBに

完全に独立させられないときはアプリケーション側で吸収

各ユーザにクラスタ番号を割り振る 各クラスタを複数の機械で構成

ndash クラスタの中の 2 3台に書き込み( 6台ではなくなった)

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 20: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 21: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 22: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 23: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

User Clustersユーザ別のクラスタの例

SELECT useridclusterid FROM user WHERE user=bob

userid 839clusterid 2

SELECT FROM WHERE userid=839

OMG i like totally hate my parents they just dont understand me and i h8 the world omg lol rofl ^-^^

add me as a friend

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 24: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Details詳細

per-user numberspacesndash dont use AUTO_INCREMENTndash PRIMARY KEY (user_id

thing_id)ndash so

Can moveupgrade users 1-at-a-timendash per-user ldquoreadonlyrdquo flagndash per-user ldquoschema_verrdquo propertyndash user-moving harness

job server that coordinates distributed long-lived user-mover clients who ask for tasks

ndash balancing disk IO disk space

ユーザごとに新たな番号を振るndash MySQLの AUTO_INCREMENTは使わない

ndash PRIMARY KEY (user_id thing_id)

ndash so 移動変更はユーザごとにできる

ndash ユーザごとに readonlyフラグを立てる

ndash ユーザごとに schema_verを記録

ndash ユーザの移動をするしくみ 負荷の高いクライアントをからユーザを移動させるジョブサーバをつくる

ndash ディスク IOやディスク容量を均衡にできる

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 25: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Shared Storage共用ディスク (SAN SCSI DRBD)

Turn pair of InnoDB machines into a clusterndash looks like 1 box to outside world

floating IP One machine at a time running fs

MySQL Heartbeat to move IP unmount

filesystem stopstart mysql No special schema considerations MySQL 41 w binlog syncflush

optionsndash goodndash The cluster can be a master or

slave as well

InnoDBを使った機械のペアをクラスタ化ndash 外からは 1台に見えるひとつの IPが機械間を移動

1台のみ FSとMySQLを運用 Heartbeatをもとに IPを移動ファイルシステムの アン マウント stop start mysql

特別にスキーマを設計したりしなくてよい

MySQL 41で binlog syncflushのオプションで運用ndash いい感じndash クラスタはマスタにもスレーブにもなれる

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 26: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Shared Storage DRBD

Linux block device driverndash ldquoNetwork RAID 1rdquondash Shared storage without

sharingndash sits atop another block

devicendash syncs w another machines

block device cross-over gigabit cable

ideal network is faster than random writes on your disks

InnoDB on DRBD HA MySQLndash can hang slaves off floater

IP

Linux上のブロックデバイスドライバndash ネットワーク上の RAID 1と呼ばれる

ndash 共有ディスクではなくデータを共有

ndash ブロックデバイスの上で動作ndash ほかの機械のブロックデバイスへミラー

クロスオーバギガビットケーブルが理想ネットワークはディスクへのランダム書き込みより速い

InnoDBと DRBDの組み合わせMySQLの HAndash スレーブを浮動する IPの上に置ける

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 27: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

MySQL Clustering OptionsPros amp Cons

MySQL のクラスタリングの方法いろいろ長所と短所 no magic bullet 特効薬はない

ndash Masterslavendash Mastermasterndash DRBDndash MySQL Clusterndash

lots of options やり方はたくさんndash )ndash (

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 28: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Part IIOur Software

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 29: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Caching

cachings key to performancendash store result of a computation or

IO for quicker future access Where to cache

ndash mod_perl caching memory waste (address

space per apache child)ndash shared memory

limited to single machine same with JavaCMono

ndash MySQL query cache flushed per update small

max sizendash HEAP tables

fixed length rows small max size

キャッシュこそがパフォーマンスの鍵ndash 計算や IOを走らせた後の結果を保存してあとで使う

どこでキャッシュすべきかndash mod_perl caching

mod_perl上のキャッシュはメモリの無駄使い

ndash shared memory 共有メモリは1台のマシン上でしか共有できない

ndash MySQL query cache MySQLはアップデート毎にディスク IOが走るし容量の限界が小さい

ndash HEAP tables メモりヒープテーブルは固定長容量の限界が小さい

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 30: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

memcachedhttpwwwdangacommemcached

our Open Source distributed caching system

run instances wherever free memory

two-level hashndash client hashes to serverndash server has internal hash

table no ldquomaster noderdquo protocol simple XML-free

ndash perl java php python ruby

popular fast

オープンソースの分散型キャッシュシステム

どのマシンでもいいからメモリが余ってるところで走らせればいい

2段階のハッシュndash クライアントはどのサーバに接続すればよいかのハッシュを持っており

ndash サーバも内部的なハッシュテーブルを持っている

「マスター」は存在しない シンプルなプロトコール XMLなんか使わないよndash perl java php python ruby

皆に好評だしhellip 速い

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 31: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Perlbal

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 32: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Web Load Balancingロードバランサー

BIG-IP Alteon Juniper Foundryndash good for L4 or minimal L7ndash not tricky fun enough -)

Tried a dozen reverse proxiesndash none did what we wanted or

were fast enough Wrote Perlbal

ndash fast smart manageable HTTP web server reverse proxy LB

ndash can do internal redirects and dozen other tricks

BIG-IP Alteon Juniper Foundryndash L4や最小限の L7には対応しているんだけどhellip

ndash ちょっと物足りなかった -) リバースプロキシも色々試してみたndash どれもやりたかった事が実現できなかったり遅すぎたりした

結果的に Perlbalを書く事にndash 高速で頭が良くて管理も簡単な ウェブサーバープロキシロードバランサー

ndash 内部でのリダイレクトにも対応

もちろんその他に色々細かい技を使える

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 33: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Perlbal

Perl single threaded async event-

basedndash uses epoll kqueue etc

console HTTP remote managementndash live config changes

handles dead nodes smart balancing

multiple modesndash static webserverndash reverse proxyndash plug-ins (Javascript message

bus) plug-ins

ndash GIFPNG altering

Perl シングルスレッド非同期イベントベースndash epoll kqueue etc

コンソール HTTP リモートマネージメントndash 動的設定変更

死んだノードを処理できるかしこい分散

複数のモードndash 静的Webサーバndash リバースプロキシndash プラグイン (Javascript メッセージバス )

plug-insndash GIFPNGのパレットを変換したり

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 34: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Perlbal Persistent Connections永続的な接続

perlbal to backends (mod_perls)ndash know exactly when a

connection is ready for a new request

no complex load balancing logic just use whatevers free beats managing ldquoweighted round robinrdquo hell

clients persistent not tied to backend

perlbalからアプリサーバーndash アプリサーバーがいつ新しいリクエストを処理できるのか分かってる

小難しいロードバランスはしないでただ次に使える接続を使う

クライアント側も永続的な接続を使うでもアプリサーバと永続的に接続をするとは限らない

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 35: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Perlbal verify new connections新規接続のチェックも行う

connects often fast but talking to kernel not apache (listen queue)ndash send OPTIONs request

to see if apache is there Huge improvement to

user-visible latency

アプリサーバが接続に応答してもカーネルに接続してい

るだけでApacheが応答したとは限らないndash OPTIONリクエストを投げてApacheが応答しているか確認する

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 36: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Perlbal multiple queues複数レベルのキュー

high normal low priority (idle bots) queues キューの優先度が高いものから低いもの(ボットや待機状態のもの)

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 37: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Perlbal cooperative large file serving

large file serving w mod_perl badndash mod_perl has better

things to do than spoon-feed clients bytes

mod_perlで大きいファイルを送信するのは良くないndash mod_perlサーバーにはデータをそのまま送るような簡単な仕事よりもっと重要な事をしてもらいたい

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 38: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Perlbal cooperative large file serving

internal redirectsndash mod_perl can pass off

serving a big file to Perlbal

either from disk or from other URL(s)

ndash client sees no HTTP redirect

ndash ldquoFriends-onlyrdquo images one clean URL mod_perl does auth and

is done perlbal serves

内部リダイレクトndash 大きいファイルはPerlbalに処理してもらう

ディスクからでも他のURLからでも

ndash クライアント自体はリダイレクトされたとわからない

ndash 例えば友達しか見れない画像とか

変なURLを使う必要なし

mod_perlは認証をするだけ

画像自体は perlbalが処理する

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 39: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Internal redirect picture

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 40: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

MogileFS

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 41: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

oMgFileS

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 42: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

MogileFS

our distributed file system

open source userspace hardly unique

ndash Google GFSndash Nutch Distributed File

System (NDFS) production-quality

ndash lot of users

分散ファイルシステム オープンソース ユーザースペース 同様の仕組み

ndash Google GFSndash Nutch Distributed File

System (NDFS) 製品レベルの品質

ndash ユーザーも多い

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 43: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

MogileFS Why

alternatives at time were eitherndash closed non-existent

expensive in development complicated

ndash scaryimpossible when it came to data recovery

newuncommon unstudied on-disk formats

because it was easyndash initial version = 1 weekend

開発前の選択肢はいずれもndash クローズドな 今までにない 高価な 開発中の 複雑な

ndash データのリカバリが恐ろしい 不可能

新しい普通でない考え抜かれていないディスク上のフォーマット

簡単だったからndash 最初のバージョン = 週末で完成

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 44: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

MogileFS Main IdeasMogileFS の考え方

files belong to classes which dictatendash replication policy min

replicas tracks what disks files are on

ndash set disks state (up temp_down dead) and host

keep replicas on devices on different hostsndash (default class policy)ndash No RAID (for this for

databases its good) multiple tracker databases

ndash all share same database cluster (MySQL etc)

big cheap disksndash dumb storage nodes w 12

16 disks no RAID

ファイルはクラスに属している クラスで決めているのは ndash レプリケーションポリシー レプリカの最小数

ファイルがどのディスクにあるかを調べてndash ディスクの状態 (up 一時的な down 死亡 )とホストをセットする

別のホストのデバイスにレプリカをもつndash (デフォルトのクラスポリシー )ndash RAID不要

複数のトラッカーデータベースndash トラッカーは同じデータベースクラスタを共有 (MySQL他 )

大きい安いディスクを並べるndash 12 16ディスクの大きいストレージノードRAIDは無し

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 45: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

MogileFS components

clients trackers database(s) (MySQL abstract) storage nodes

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 46: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

MogileFS Clients

tiny text-based protocol 小さいテキストベースのプロトコル

Libraries available for 使えるライブラリ ndash Perl

tied filehandles (tieされたファイルハンドル ) MogileFSClient

ndash my $fh = $mogc-gtnew_file(ldquokeyrdquo [[$class] ])ndash Javandash PHPndash Pythonndash porting to $LANG is be trivial 移植は簡単

future no custom protocol only HTTP PUT to trackers doesnt do database access データーべースアクセス不要

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 47: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

MogileFS Tracker(mogilefsd)

The Meat 心臓部 event-based message bus イベントベースのメッセージバスndash load balances client requests world info クライアントの要求を負荷分散するworld info

process manager プロセスマネージャーndash heartbeatswatchdog respawner

Child processes 子プロセスndash ~30x client interface (ldquoqueryrdquo process)

interfaces client protocol w db(s) etcndash ~5x replicatendash ~2x deletendash ~1x monitoringndash

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 48: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Trackers Database(s)トラッカーのデータベース

Abstract as of Mogile 2x Mogile 2x 時点の抜粋ndash MySQLndash SQLite (jokedemo)ndash PgOracle coming soonndash Also future これもそのうち

wrapper driver partitioning any abovendash small metadata in one driver (MySQL Cluster)ndash 一つのドライバに小さいメタデータ (MySQL Cluster)ndash large tables partitioned over 2-node HA pairs ndash 2ノードのHAペア上のパーティション分けされた大きいテーブル

Recommend config 推奨設定ndash 2xMySQL InnoDB on DRBDndash 2 slaves underneath HA VIP HAの大物の下に 2つのスレーブ

1 for backups 一つはバックアップに read-only slave for during master failover window マスターがフェイルオーバーしている間のリードオンリーのスレーブ

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 49: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

MogileFS storage nodesMogileFS ストレージノード

HTTP transportndash GETndash PUTndash DELETE

Pick a server サーバの選択 ndash mogstored (recommended ldquouse Perlbalrdquo)

side-channel iostat interface AIO control ndash Apache+mod_davndash lighttpd

files on filesystem not DB ファイルシステムにファイルがあるDBではないndash sendfile() future splice()ndash filesystem can be any filesystemndash どんなファイルシステムでもOK

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 50: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Large file GET

request

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 51: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Large file GET

request

Auth complex but quick認証 複雑でも速い

Spoonfeeding slow but event-basedスプーンフィーディング 遅いけどイベントベース

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 52: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

And the reverse逆に

Now Perlbal can buffer uploads as wellndash Problems

LifeBlog uploadingndash cellphones are slow

LiveJournalFriendster photo uploadsndash cableDSL uploads still

slowndash decide to buffer to ldquodiskrdquo

(tmpfs likely) on any of rate size time

Perlbalはアップロードをバッファできるが ndash 問題

日記ブログのアップロードndash 携帯電話は遅い

LiveJournalFriendster の写真アップロードndash ケーブル DSLアップロードもまだ遅い

ndash ldquodiskrdquoにバッファすることに決めた (tmpfsが有望 )

いずれも rate サイズ時間

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 53: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Gearman

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 54: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

manaGer

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 55: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Managerdispatches work

but doesnt do anything useful itself )

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 56: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Gearman

low-latency remote function call ldquorouterrdquo

client wants results arguments to submit a jobndash opaque bytes ldquofunction

namerdquondash opt opaque ldquofunction argsrdquo

(Storable )ndash opt coalescing value

can multiplex results of slow call back to multiple waiting callers

待ち時間の少ないリモートファンクションコール ldquoルータrdquo

クライアントは結果がほしい引数にジョブをあたえる ndash 第一引数にldquo関数名rdquondash (オプション )第二引数にldquo関数の引数rdquo (Storable )

ndash (オプション ) 値をくっつける

複数の待っているクライアントへ複数の遅延コールバックの結果を多重送信できる

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 57: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Gearman Protocol

binary protocolndash future C server clientndash currently gearmand doesnt

use much CPU solution we need to push

it harder )

バイナリプロトコルndash 将来 C サーバ クライアント

ndash 現在 gearmand は CPUをそんなに使わない

解決 もっと使い倒さないと )

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 58: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Gearman UsesGearman を使うと

ImageMagick outside of your mod_perls

DBI connection pooling (DBDGofer + Gearman)

reducing load improving visibility

ldquoservicesrdquondash can all be in different

languages too

ImageMagickをmod_perlから追い出せる

DBI 接続のプーリング(DBDGofer + Gearman)

負荷が減る improving visibility

ldquoサービスrdquondash can all be in different

languages too

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 59: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Gearman Uses cont

running code in parallelndash query ten databases at

once running blocking code

from event loopsndash DBI from

POEDangaSocket apps

spreading CPU from ev loop daemons

並列にコードが動くndash 一回で 10のデータベースに問い合わせる

イベントループからブロッキングコードを実行ndash POEDangaSocketアプリケーションからDBIを

イベントループデーモンから

CPU を拡散する

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 60: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Gearman Pieces

gearmandndash dumb routerndash event-loop Now Perl

Future C workers

ndash GearmanWorker ndash perlndash registerheartbeatgrab jobs

clientsndash GearmanClient[Async]ndash submit jobs to gearmandndash hash onto a gearmand

optimization for coalescing can use any on failure

gearmandndash 頭の悪いルータndash イベントループ現在

Perlそのうち C workers

ndash GearmanWorker ndash perlndash ジョブの登録 監視 取得

clientsndash GearmanClient[Async]ndash gearmandにジョブを投げるndash hash onto a gearmand

くっつけるのに最適化している

失敗時に何でも使える

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 61: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Gearman Pictureca

ll(ldquof

uncA

rdquo ldquoa

rgrdquo)

can_do(ldquofuncArdquo)can_do(ldquofuncBrdquo)

client worker worker

gearmand gearmand gearmand

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 62: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Gearman Misc

Guaranteesndash none hah )

please wait for your results

if client goes away no promises

No policyconventions in gearmandndash all policymeaning

between clients lt-gt workers

保証 ndash 無し hah )

結果を待ってください クライアントが停止しても特に保証はない

gearmandにはポリシーも約束もないndash 全てのポリシー 意味は

clients lt-gt workersの間にある

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 63: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Gearman Summary

Gearman is sexyndash especially the

coalescing Check it out

ndash its kinda our little unadvertised secret

oh crap did I leak the secret

Gearmanはセクシーndash 特に coalescing

チェック ndash これはちょっとあんまり宣伝してない秘密

やばい秘密を漏らしちゃったかな

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 64: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

TheSchwartz

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 65: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

TheSchwartz

Like gearmanndash job queuing systemndash opaque function namendash opaque ldquoargsrdquo blobndash clients are either

submitting jobs workers

But not like gearmanndash Reliable job queueing

systemndash not necessarily low latency

currently library not network service

Like gearman 頼できるジョブのキューシステム

現在はライブラリネットワークサービスではない

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 66: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

TheSchwartz Primitives

insert job ldquograbrdquo job (atomic

grab)ndash for n seconds

mark job done temp fail job for future

ndash optional notes rescheduling details

replace job with 1+ other jobsndash atomic

ジョブの挿入 ジョブをldquoつか

むrdquo (atomic grab)ndash n秒間

ジョブに終わった印を付ける 一時的な失敗

ndash 備考や再スケジュール 一つ以上の他のジョブへリプレースndash アトミック

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 67: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

TheSchwartz

backing storendash a databasendash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

ストレージndash データベースndash uses DataObjectDriver

MySQL Postgres SQLite

but HA you tell it dbs and it finds one to insert job intondash likewise workers foreach

(dbs) to do work

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 68: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

TheSchwartz uses

outgoing email (SMTP client)ndash millions of emails per day

LJ notificationsndash ESN event subscription

notification one event (new post etc)

-gt thousands of emails SMSes XMPP messages etc

pinging external services atomstream injection dozens of users shared farm for TypePad Vox LJ

メール配信 (SMTP クライアント )ndash 一日に数百万のメール

LiveJournalの通知ndash ESN イベント (Event)サブスクリプション (Subscription)通知 (Notification)

あるイベント (新しい投稿など ) -gt 数千のメールショートメッセージXMPPメッセージ他

他のサービスへの ping atomstreamの挿入 数十のユーザー TypePad Vox LiveJournalで共有のファーム

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 69: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

gearmand + TheSchwartz

gearmand not reliable low-latency no disks

TheSchwartz latency reliable disks

In TypePadndash TheSchwartz with

gearman to fire off TheSchwartz workers

disks but low-latency future no disks

SSDFlash MySQL Cluster

gearmand 保証無し少ない待ち時間ディスク不要

TheSchwartz 待ち時間信頼できるディスクを使う

TypePad では ndash Gearmanが

TheSchwartz ワーカーを起動させる

ディスクを使うが待ち時間は少ない

そのうち ディスクを使わずにSSDFlashMySQL Cluster

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 70: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

djabberd

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 71: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

djabberd

Our JabberLJTalk server

S2S works with GoogleTalk etc

perl event-based (epoll etc)

done 300000+ conns tiny per-conn memory

overheadndash release XML parser

state if possible

Our JabberLJTalk server

S2S works with GoogleTalk etc

perlイベントベース (epoll など )

300000以上の接続を行う 接続ごとのメモリのオーバーヘッドが小さいndash 可能ならXMLパーサーの状態を更新する

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 72: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

djabberd hooks

everything is a hookndash not just auth like

everythingndash ala mod_perl qpsmtpd

etcndash inter-node

communication async hooks

ndash use GearmanClientAsync

ndash async Gearman client for DangaSocket-based apps

全てはフックndash 認証だけでない 全部ndash mod_perlや qpsmtpdなどのように

ndash ノード間のコミュニケーション

非同期のフックndash use

GearmanClientAsyncndash DangaSocketベースのアプリ用の非同期のGearmanクライアント

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 73: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Thank you

Questions tobraddangacom

Softwarehttpdangacom

httpcodesixapartcom

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 74: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Bonus Slides

if extra time

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 75: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Data Integrity

Databases depend on fsync()ndash but databases cant send raw SCSIATA commands

to flush controller caches etc fsync() almost never works work

ndash Linux FS (lack of) barriers raid cards controllers disks

Solution test amp fixndash disk-checkerpl

clientserver spew writesfsyncs record intentions on alive machine

yank power checks

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman

Page 76: LiveJournal: Behind The Scenes · MySQL Heartbeat to move IP, {un,}mount filesystem, {stop,start} mysql No special schema considerations MySQL 4.1 w/ binlog sync/flush options –

httpwwwdangacomwords

Persistent Connection Woes

connections == threads == memoryndash My pet peeve

want connectionthread distinction in MySQL w max-runnable-threads tunable

max threadsndash limit max memoryconcurrency

DBDGofer + Gearmanndash Ask

DataObjectDriver + Gearman