中级农民
- 积分
- 105
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2012-5-31
- 最后登录
- 1970-1-1
|
Grokking System Design - Design twitter - Data Sharding
What if we can combine sharding by TweedID and Tweet creation time?
If we don’t store tweet creation time separately and use TweetID to reflect that, we can get benefits of both the approaches.
This way it will be quite quick to find latest Tweets. For this, we must make each TweetID universally
unique in our system, and each TweetID should contain timestamp too.
We can use epoch time for this. Let’s say our TweetID will have two parts; the first part will be
representing epoch seconds and the second part will be an auto-incrementing sequence. So, to make a
new TweetID, we can take the current epoch time and append an auto-incrementing number to it. We
can figure out shard number from this TweetID and store it there.
What could be the size of our TweetID? Let’s say our epoch time starts today, how many bits we would
need to store the number of seconds for next 50 years?
86400 sec/day * 365 (days a year) * 50 (years) => 1.6B
We would need 31 bits to store this number. Since on average we are expecting 1150 new tweets per
second, we can allocate 17 bits to store auto incremented sequence; this will make our TweetID 48 bits
long. So, every second we can store (2^17 => 130K) new tweets. We can reset our auto incrementing
sequence every second. For fault tolerance and better performance, we can have two database servers to
generate auto-incrementing keys for us, one generating even numbered keys and the other generating
odd numbered keys.
If we assume our current epoch seconds are “1483228800”, our TweetID will look like this:
1483228800 000001
1483228800 000002
1483228800 000003
1483228800 000004
…
If we make our TweetID 64bits (8 bytes) long, we can easily store tweets for next 100 years and also store
them for mili-seconds granularity. |
|