RedisとMongoDBについて調べた
『Play (Scala) + Redisで作ろうか』という思いつきの実現可能性を検討した。Redisも使えるかもしれないし、MongoDBのほうが使えるかもしれない。それはそもそも永続化の方式に依存する。
Redisの扱えるキー数はメモリ容量の制約を受ける
memcachedと“正反対”、Redisが仮想メモリをサポート - @IT:
キーがすべてメモリに乗っていることから、Redisの高速性は保たれるというわけだ。また実際のバリューのほうがいくら大きくなっても、メモリ消費量はキーの数にだけ依存することになり、100万キー当たり160MBのメモリ消費で済むという。
1億キー扱うには16GBのメモリが必要だ。まあ、そのときはスケールアップ(メモリ増強)かスケールアウト(分散化)すればよいのだが。サーバー2台で1億キー。MySQLやPostgreSQLと比べても、そんなにバランスが悪いわけではなさそう。ここでいう「バランス」とは、高速性とデータ規模のバランス。
KVSをプライマリーデータベースにした設計事例
TwitterアプリにおけるRedisデータベースの設計事例:
- uid:(user ID):username
- username:(username):uid => user ID / reverse index
- uid:(user ID):password
- uid:(user ID):auth => session ID
- auth:(session ID) => user ID / reverse index
- uid:(user ID):followers => Set of uids of all the followers users
- uid:(user ID):following => Set of uids of all the following users
- uid:(user ID):posts => a List of post ids, every new post is LPUSHed here.
Redis has some data types: hash, list, set and sorted set.
Before, I don't know how can I deal collective operations, such as "count up" or "total". Now I know the answer. Redis has commands for that purpose:
DDD and Redis
Domain-driven design technique categorises every objects into three: entity, value objects and aggregate.
I will make entities, value objects and aggregates persistent on KVS by following these steps:
- Serialise entities with value objects.
- Store serialised entities as values with keys set its IDs.
- Store IDs into a collection which aggregates these objects. Aggregates have their own IDs.
example:
SET person:123 (serialised object)
SET family:456 (serialised object)
SADD family:456:member 123
SADD families 456
An entity has an identity. An identity is a key.
A value object does not have any identity. A value object does not need to have a key.
Search
I do not care about search on KVS. Instead, I will use a search engine.
- Apache Lucene - Apache Solr
- Full Text Search Options on Heroku | Heroku Dev Center
- seratch/scalikesolr · GitHub
Redis vs MongoDB vs RDB
しかし、そもそもRedisなのか。同じ「NoSQL」でも、MongoDBはドキュメント指向(document-oriented database)、RedisはKVS(key-value store)であって、別物。制約が多くて使いづらい面もある。使いやすいのはMongoDBのほう。
みたいなことを考えた。
追記
- データベースを使った永続化への復讐(2013-02-03)
- Redisによる透明な永続化層(2013-02-15)