88
Handling 20 billion requests a month? Easy

Handling 20 billion requests a month

Embed Size (px)

Citation preview

Page 1: Handling 20 billion requests a month

Handling 20 billion requests a month? Easy

Page 2: Handling 20 billion requests a month

Dmitriy DumanskiyCogniance, mGage project

Java Team Lead

Java blog : habrahabr.ru/users/doom369/topics

Page 3: Handling 20 billion requests a month

Project evolution

Ad Project 1 Ad Project 2

XXXX

Page 4: Handling 20 billion requests a month

Ad Project 1 delivery load

3 billions req/mon. ~8 c3.xLarge Amazon instances.

Average load : 2400 req/secPeak : x10

Page 5: Handling 20 billion requests a month

Ad Project 2 delivery load

14 billions req/mon. ~16 c3.xLarge Amazon

instances.Average load : 6000 req/sec

Peak : x6

Page 6: Handling 20 billion requests a month

XXXX delivery Load

20 billions req/mon. ~14 c3.xLarge Amazon instances.

Average load : 11000 req/secPeak : x6

Page 7: Handling 20 billion requests a month

Is it a lot?

Average load : 11000 req/sec

Page 8: Handling 20 billion requests a month

Twitter : new tweets

15 billions a month Average load : 5700 req/sec

Peak : x30

Page 9: Handling 20 billion requests a month

Delivery load

Requests per month

Max load per

instance, req/sec

RequirementsServers, AWS c3.xLarge

Ad Project 1 3 billions 300 HTTPTime 95% < 60ms 8

Ad Project 2 14 billions 400 HTTPTime 95% < 100ms 16

XXXX 20 billions 800 HTTPSTime 99% < 100ms 14

Page 10: Handling 20 billion requests a month

Delivery load

c3.XLarge - 4 vCPU, 2.8 GHz Intel Xeon E5-2680LA - ~2-3

1-2 cores reserved for sudden peaks

Page 11: Handling 20 billion requests a month

BE tech stacksAd Project 2: Spring, iBatis, MySql, Solr, Vertica, Cascading, Tomcat

Ad Project 1 :Spring, Hibernate, Postgres, Distributed ehCache, Hadoop, Voldemort, Jboss

XXXX:Spring, Hibernate, MySQL, Solr, Cascading, Redis, Tomcat

Page 12: Handling 20 billion requests a month

Real problem

● ~85 mln active users, ~115 mln registered users● 11.5 messages per user per day● ~11000 req/sec● Peaks 6x● 99% HTTPS with response time < 100ms● Reliable and scalable for future grow up to 80k

Page 13: Handling 20 billion requests a month

Architecture

AdServer Console (UI)

Reporting

Page 14: Handling 20 billion requests a month

Architecture

Console (UI)

MySql

SOLR Master

SOLR Slave SOLR SlaveSOLR Slave

Page 15: Handling 20 billion requests a month

SOLR? Why?● Pros:

○ Quick search on complex queries○ Has a lot of build-in features (push-

notifications, master-slave replication, RDBMS integration)

● Cons:○ Only HTTP, embedded performs worth○ Not easy for beginners○ Max load is ~100 req/sec per instance

Page 16: Handling 20 billion requests a month

“Simple” query

"-(-connectionTypes:"+"\""+getConnectionType()+"\""+" AND connectionTypes:[* TO *]) AND "+"-connectionTypeExcludes:"+"\""+getConnectionType()+"\""+" AND " + "-(-

OSes:"+"(\""+osQuery+"\" OR \""+getOS()+"\")"+" AND OSes:[* TO *]) AND " + "-osExcludes:"+"(\""+osQuery+"\" OR \""+getOS()+"\")" "AND (runOfNetwork:T OR

appIncludes:"+getAppId()+" OR pubIncludes:"+getPubId()+" OR categories:("+categoryList+"))" +" AND -appExcludes:"+getAppId()+" AND -pubExcludes:"

+getPubId()+" AND -categoryExcludes:("+categoryList+") AND " + keywordQuery+" AND " + "-(-devices:"+"\""+getHandsetNormalized()+"\""+" AND devices:[* TO *]) AND " + "-deviceExcludes:"+"\""+getHandsetNormalized()+"\""+" AND " + "-(-carriers:"+"\""

+getCarrier()+"\""+" AND carriers:[* TO *]) AND " + "-carrierExcludes:"+"\""+getCarrier()+"\""+" AND " + "-(-locales:"+"(\""+locale+"\" OR \""+langOnly+"\")"

+" AND locales:[* TO *]) AND " + "-localeExcludes:"+"(\""+locale+"\" OR \""+langOnly+"\") AND " + "-(-segments:("+segmentQuery+") AND segments:[* TO *]) AND " + "-segmentExcludes:("+segmentQuery+")" + " AND -(-geos:"+geoQuery+" AND geos:[*

TO *]) AND " + "-geosExcludes:"+geoQuery

Page 17: Handling 20 billion requests a month

Solr

Index size < 1 Gb - response time 20-30 msIndex size < 100 Gb - response time 1-2 secIndex size < 400 Gb - response time from 10

secs

Page 18: Handling 20 billion requests a month

Architecture

MySql

Solr Master

SOLR Slave

AdServer

SOLR Slave

AdServer

SOLR Slave

AdServer

No-SQL

Page 19: Handling 20 billion requests a month

AdServer - Solr Slave

Delivery:volatile DeliveryData cache;

Cron Job:DeliveryData tempCache = loadData();

cache = tempCache;

Page 20: Handling 20 billion requests a month

Why no-sql?

● Realtime data● Quick response time● Simple queries by key● 1-2 queries to no-sql on every request. Average load

10-20k req/sec and >120k req/sec in peaks. ● Cheap solution

Page 21: Handling 20 billion requests a month

Why Redis? Pros

● Easy and light-weight● Low latency and response time.

99% is < 1ms. Average latency is ~0.2ms● Up to 100k 'get' commands per second on

c1.X-Large● Cool features (atomic increments, sets,

hashes)● Ready AWS service — ElastiCache

Page 22: Handling 20 billion requests a month

Why Redis? Cons

● Single-threaded from the box● Utilize all cores - sharding/clustering● Scaling/failover not easy● Limited up to max instance memory (240GB largest

AWS)● Persistence/swapping may delay response● Cluster solution not production ready● Data loss possible

Page 23: Handling 20 billion requests a month

DynamoDB vs RedisPrice per month Put, 95% Get, 95% Rec/sec

DynamoDB 58$ 300ms 150ms 50

DynamoDB 580$ 60ms 8ms 780

DynamoDB 5800$ 16ms 8ms 1250

Redis 200$ (c1.medium) 3ms <1ms 4000

ElastiCache 600$ (c1.xlarge) <1ms <1ms 10000

Page 24: Handling 20 billion requests a month

What about others?

● Cassandra● Voldemort● Memcached

Page 25: Handling 20 billion requests a month

Redis RAM problem

● 1 user entry ~ from 80 bytes to 3kb● ~85 mln users● Required RAM ~ from 1 GB to 300 GB

Page 26: Handling 20 billion requests a month

Data compression

Json → Kryo binary → 4x times less data → Gzipping → 2x times less data == 8x less data

Now we need < 40 GB

+ Less load on network stack

Page 27: Handling 20 billion requests a month

AdServer BE

Average response time — ~1.2 msLoad — 800 req/sec with LA ~4

c3.XLarge == 4 vCPU

Page 28: Handling 20 billion requests a month

AdServer BE

● Logging — 12% of time (5% on SSD);● Response generation — 15% of time;● Redis request — 50% of time;● All business logic — 23% of time;

Page 29: Handling 20 billion requests a month

Reporting

AdServer Hadoop ETL

MySQLConsole

S3 S3

Delivery logs Aggregated logs

1 hour batch

Page 30: Handling 20 billion requests a month

Delivery log structure{ "uid":"test", "platform":"android", "app":"xxx", "ts":1375952275223, "pid":1, "education":"Some-Highschool-or-less", "type":"new", "sh":1280, "appver":"6.4.34", "country":"AU", "time":"Sat, 03 August 2013 10:30:39 +0200", "deviceGroup":7, "rid":"fc389d966438478e9554ed15d27713f51", "responseCode":200, "event":"ad", "device":"N95", "sw":768, "ageGroup":"18-24", "preferences":["beer","girls"] }

Page 31: Handling 20 billion requests a month

Log structure

● 1 mln. records == 0.6 GB.● ~900 mln records a day == ~0.55 TB.● 1 month up to 20 TB of data.● Zipped data is 10 times less.

Page 32: Handling 20 billion requests a month

Reporting

Customer : “And we need fancy reporting”

But 20 TB of data per month is huge. So what we can do?

Page 33: Handling 20 billion requests a month

ReportingDimensions:device, os, osVer, sreenWidth, screenHeight, country, region, city, carrier, advertisingId, preferences, gender, age, income, sector, company, language, etc...

Use case:I want to know how many users saw my ad in San-Francisco.

Page 34: Handling 20 billion requests a month

ReportingGeo table:Country, City, Region, CampaignId, Date, counters;

Device table:Device, Carrier, Platform, CampaignId, Date, counters;

Uniques table:CampaignId, UID

Page 35: Handling 20 billion requests a month

Predefined report types → aggregation by predefined dimensions → 500-1000 times less

data 20 TB per month → 40 GB per month

Page 36: Handling 20 billion requests a month

Of course - hadoop● Pros:

○ Unlimited (depends) horizontal scaling

● Cons:○ Not real-time○ Processing time directly depends on quality code

and on infrastructure cost.○ Not all input can be scaled○ Cluster startup is so... long

Page 37: Handling 20 billion requests a month

Timing● Hadoop (cascading) :

○ 25 GB in peak hour takes ~40min (-10 min). CSV output 300MB. With cluster of 4 c3.xLarge.

● MySQL:○ Put 300MB in DB with insert statements ~40 min.

Page 38: Handling 20 billion requests a month

Timing● Hadoop (cascading) :

○ 25 GB in peak hour takes ~40min (-10 min). CSV output 300MB. With cluster of 4 c3.xLarge.

● MySQL:○ Put 300MB in DB with insert statements ~40 min.

● MySQL:○ Put 300MB in DB with optimizations ~5 min.

Page 39: Handling 20 billion requests a month

Optimized are

● No “insert into”. Only “load data” - ~10 times faster● “ENGINE=MyISAM“ vs “INNODB” when possible - ~5

times faster● For “upsert” - temp table with “ENGINE=MEMORY” - IO

savings

Page 40: Handling 20 billion requests a month

CascadingHadoop:

void map(K key, V val,

OutputCollector collector) {

...

}

void reduce(K key, Iterator<V> vals, OutputCollector collector) {

...

}

Cascading:Scheme sinkScheme = new TextLine(new Fields( "word", "count"));

Pipe assembly = new Pipe("wordcount");

assembly = new Each(assembly, new Fields( "line" ), new RegexGenerator(new Fields("word"), ",") );

assembly = new GroupBy(assembly, new Fields( "word"));

Aggregator count = new Count(new Fields( "count"));

assembly = new Every(assembly, count);

Page 41: Handling 20 billion requests a month

Why cascading?

Hadoop Job 1

Hadoop Job 2

Hadoop Job 3

Result of one job should be processed by another job

Page 42: Handling 20 billion requests a month

Lessons Learned

Page 43: Handling 20 billion requests a month

Facts

● HTTP x2 faster HTTPS● HTTPS keep-alive +80% performance● Java 7 40% faster Java 6 (our case)● All IO operations minimized● Less OOP - better performance

Page 44: Handling 20 billion requests a month

Cost of IO

L1 cache 3 cyclesL2 cache 14 cyclesRAM 250 cyclesDisk 41 000 000 cyclesNetwork 240 000 000 cycles

Page 45: Handling 20 billion requests a month

Cost of IO

@Cacheable is everywhere

Page 46: Handling 20 billion requests a month

Java 7. Random

return items.get(new Random().nextInt(items.size()))

Page 47: Handling 20 billion requests a month

Java 7. Random

return items.get(ThreadLocalRandom().current().nextInt(items.size()))

~3x

Page 48: Handling 20 billion requests a month

Java 7. Less garbage

new ArrayList():this.elementData = {};

insteadOf

this.elementData = new Object[10];

new HashMap():Entry<K,V>[] table = {};

insteadOf

this.table = new Entry[16];

Page 49: Handling 20 billion requests a month

Java 7. Less garbage

Before:class String {

int offset;

int count;

char value[];

int hash;

}

After:class String {

char value[];

int hash;

}

Page 50: Handling 20 billion requests a month

Java 7. GC

200mb per second - 0.5% CPU time

Smaller heap - better performance

Page 51: Handling 20 billion requests a month

Java 7. String

● Substring● Split

Page 52: Handling 20 billion requests a month

Use latest versions

Jedis 2.2.3 uses commons-pool 1.6Jedis 2.3 uses commons-pool 2.0

commons-pool 2.0 - ~2x times faster

Page 53: Handling 20 billion requests a month

Small tweaks. Date

new Date() vs

System.currentTimeMillis()

Page 54: Handling 20 billion requests a month

Small tweaks. SimpleDateFormat

return new SimpleDateFormat(“MMM yyyy HH:mm:ss Z”).parse(dateString)

Page 55: Handling 20 billion requests a month

Small tweaks. SimpleDateFormat

● ThreadLocal● Joda - threadsafe DateTimeFormat

Page 56: Handling 20 billion requests a month

Small tweaks. Pattern

public Item isValid(String ip) {

Pattern pattern = Pattern.compile("xxx");

Matcher matcher = pattern.matcher(ip);

return matcher.matches();

}

Page 57: Handling 20 billion requests a month

Small tweaks. Pattern

final Pattern pattern = Pattern.compile("xxx");

final Matcher matcher = pattern.matcher(“”);

public Item isValid(String ip) {

matcher.reset(ip);

return matcher.matches();

}

Page 58: Handling 20 billion requests a month

Small tweaks. String.split

item.getPreferences().split(“[_,;,-]”);

Page 59: Handling 20 billion requests a month

Small tweaks. String.split

item.getPreferences().split(“[_,;,-]”);

vsstatic final Pattern PATTERN = Pattern.compile("[_,;,-]");

PATTERN.split(item.getPreferences()) - ~2x fastervs

custom code - up to 5x faster

Page 60: Handling 20 billion requests a month

Small tweaks. FOR loop

for (A a : arrayListA) {

// do something

for (B b : arrayListB) {

// do something

for (C c : arrayListC) {

// do something

}

}

}

Page 61: Handling 20 billion requests a month

Small tweaks. FOR loopfor (Iterator<A> i = arrayListA.iterator(); i.hasNext();) {

a = i.next();

}

public Iterator<E> iterator() {

return new Itr();

}

private class Itr implements Iterator<E> {

int cursor = 0;

int lastRet = -1;

int expectedModCount = modCount;

}

Page 62: Handling 20 billion requests a month

Small tweaks. FOR loop

Page 63: Handling 20 billion requests a month

Small tweaks. LinkedList

Just don’t use it

Page 64: Handling 20 billion requests a month

Small tweaks. Primitives

double coord = Double.valueOf(textLine);

Page 65: Handling 20 billion requests a month

Avoid concurrency

volatile the simplest way

Page 66: Handling 20 billion requests a month

Avoid concurrency

JedisPool.getResource() - syncJedisPool.returnResource() - syncOutputStreamWriter.write() - sync

UUID.randomUUID() - sync

Page 67: Handling 20 billion requests a month

Avoid concurrency

JedisPool.getResource()

JedisPool.returnResource()

replace with

ThreadLocal<JedisConnection>

Page 68: Handling 20 billion requests a month

Avoid concurrency

ThreadLocal<JedisConnection> - requires ~1000 open connections for Redis.

More connections — slower redis response.Dead end.

Page 69: Handling 20 billion requests a month

Avoid concurrency

OutputStreamWriter.write()

● No flush() on every request and big buffered writer ● Async writer

No guarantee for no data loss. Dead end.

Page 70: Handling 20 billion requests a month

Avoid concurrency

OutputStreamWriter.write()

Or buy SSD =)+30-60% on disk IO

Page 71: Handling 20 billion requests a month

Hadoop

Map input : 300 MBMap output : 80 GB

Page 72: Handling 20 billion requests a month

Hadoop

● mapreduce.map.output.compress = true● codecs: GZip, BZ2 - CPU intensive● codecs: LZO, Snappy● codecs: JNI

~x10

Page 73: Handling 20 billion requests a month

Hadoop

Consider Combiner

Page 74: Handling 20 billion requests a month

Hadoop

Text, IntWritable, BytesWritable, NullWritable, etc

Simpler - better

Page 75: Handling 20 billion requests a month

Hadoop

map(T value, ...) {

Log log = parse(value);

Data data = dbWrapper.getSomeMissingData(log.getCampId());

}

Page 76: Handling 20 billion requests a month

Hadoop

Missing data:map(T value, ...) {

Log log = parse(value);

Data data = dbWrapper.getSomeMissingData(log.getCampId());

}

Wrong

Page 77: Handling 20 billion requests a month

Hadoop

map(T value, ...) {

Log log = parse(value);

Key resultKey = makeKey(log.getCampName(), ...);

output.collect(resultKey, resultValue);

}

Page 78: Handling 20 billion requests a month

Hadoop

Unnecessary data:map(T value, ...) {

Log log = parse(value);

Key resultKey = makeKey(log.getCampName(), ...);

output.collect(resultKey, resultValue);

}

Wrong

Page 79: Handling 20 billion requests a month

Hadoop

RecordWriter.write(K key, V value) {

Entity entity = makeEntity(key, value);

dbWrapper.save(entity);

}

Page 80: Handling 20 billion requests a month

Hadoop

Minimize IO: RecordWriter.write(K key, V value) {

Entity entity = makeEntity(key, value);

dbWrapper.save(entity);

}

Wrong

Page 81: Handling 20 billion requests a month

Hadoop public boolean equals(Object obj) {

EqualsBuilder equalsBuilder = new EqualsBuilder();

equalsBuilder.append(id, otherKey.getId());

...

}

public int hashCode() {

HashCodeBuilder hashCodeBuilder = new HashCodeBuilder();

hashCodeBuilder.append(id);

...

}

Page 82: Handling 20 billion requests a month

Hadoop public boolean equals(Object obj) {

EqualsBuilder equalsBuilder = new EqualsBuilder();

equalsBuilder.append(id, otherKey.getId());

...

}

public int hashCode() {

HashCodeBuilder hashCodeBuilder = new HashCodeBuilder();

hashCodeBuilder.append(id);

...

}

Wrong

Page 83: Handling 20 billion requests a month

Hadooppublic void map(...) {

…for (String word : words) {

output.collect(new Text(word), new IntVal(1));

}

}

Page 84: Handling 20 billion requests a month

Hadooppublic void map(...) {

…for (String word : words) {

output.collect(new Text(word), new IntVal(1));

}

}

Wrong

Page 85: Handling 20 billion requests a month

Hadoopclass MyMapper extends Mapper {

Text word = new Text();

IntVal one = new IntVal(1);

public void map(...) {

for (String word : words) {

word.set(word);

output.collect(word, one);

}

}

}

Page 86: Handling 20 billion requests a month

Amazon

Page 87: Handling 20 billion requests a month

AWS ElastiCache

● Strange timeouts (with SO_TIMEOUT 50ms)● No replication for another cluster● «Cluster» is not a cluster● Cluster uses usual instances, so pay for 4

cores while using 1

Page 88: Handling 20 billion requests a month

AWS Limits. You never know where

● Network limit● PPS rate limit● LB limit● Cluster start time up to 20 mins● Scalability limits● S3 is slow for many files