SlideShare uma empresa Scribd logo
1 de 45
Baixar para ler offline
This talk is not a hardcore latency talk 
I will not talk about: 
•CPU caches 
•System.nanoTime 
•lockless concurrent queues 
•magic low latency framework
This talk is not a hardcore latency talk 
Scaling from 500 to 150K QPS, the hard way
Latency 
a size telling us how long something took
http://www.techempower.com/benchmarks/#section=data-r9&hw=peak&test=json 
Typical latency benchmark on the internet
Why average is a common metric? 
•Everyone understands it 
•It’s easy to calculate
Why average is a common metric? 
•Everyone understands it 
•It’s easy to calculate 
•It can also hide important unwanted behaviour of the system!
Imagine we have a service 
with the following response latencies
Calculating latency average
Calculating latency average 
20% of the requests got latency twice as above 10 ms
Percentiles 
The value below which a given percentage of observations in a group of observations fall 
Like p50% = the max value of 50% of the values
Percentiles
Percentiles in real life
Libraries for tracking latencies 
HdrHistogram: http://hdrhistogram.github.io/HdrHistogram/ 
Uses fixed memory and constant CPU for recording (C, Java, C# work in progress). 
Finagle: https://twitter.github.io/finagle/ 
Scala, Java RPC framework by Twitter, has built in stats and latency tracking.
APIs in online advertising
APIs in online advertising 
98% of requests under 100 ms
APIs in online advertising 
98% of requests under 100 ms 
HTTP
APIs in online advertising 
98% of requests under 100 ms 
HTTP 
JSON
APIs in online advertising 
98% of requests under 100 ms 
HTTP 
JSON 
Protocol Buffers
Real-time bidding API 
How much would you pay if you give us an ad of size 200x120 to show it on youtube.com for a user from Belgium, who is interested in Sports and Culture?
Real-time bidding API
1.Deserialize request 
2.Process some rules 
3.Get pre-calculated bid price from storage 
4.Calculate some more 
5.Serialize response 
Real-time bidding request processing 
All rest 40 ms for network latency 
40 ms 
60 ms
LVS + keepalived 
Profiler API 
User profiles 
Bid price calculators 
Bidder API 
Ad serving
Redis in 50 words or less 
Redis is an open source, BSD licensed, advanced key-value cache and store.
Redis as key-value store 
•Append write, flush every second 
•Operations on multiple keys 
•Works great, but watch out when writing/reading on the same node simultaneously
Redis latencies 
Simultaneous writes and reads on the same node
Cassandra in 50 words or less 
Apache Cassandra is an open source, distributed, decentralized, elastically scalable, highly available, fault-tolerant, tuneably consistent, column-oriented database
Why Cassandra is good 
•Fast writes 
•User profile is a natural key-value model 
•Easy to scale (especially with virtual nodes) 
•Seemed the most mature at that time (started using from v0.7) 
•Runs on a legacy spare HW 
•Runs on Windows :)
Why Cassandra is good 
•Fast writes 
•User profile is a natural key-value model 
•All nice features mentioned before 
•Seemed the most mature at that time (started using from v0.7) 
•Runs on a legacy spare HW 
•Runs on Windows :)
Why Cassandra is not so good
Why Cassandra is not so good 
GC pauses
Cassandra tuning tricks that worked 
•LeveledCompactionStrategy 
•Changing Java heap size (8 GB) 
•Client direct read of data (token aware strategy)
Cassandra tuning tricks that did not work 
GC tuning
Cassandra tuning tricks that did not work 
GC tuning 
20% of requests exceeding 40 ms
Connecting to Cassandra 
Thrift version
Fail fast plan 
1.Set a TSocket timeout to 10 ms 
2.If node does not answer under 10 ms, try another from the same range 
3.Repeat this 3 times
Timeouts in .NET are broken 
•.NET Socket SendReceiveTimeout does not work for values less than 500 ms 
•Same applies to SocketAsyncEventArgs 
•Async version even worse (timer queues, etc.)
Thing that worked 
Socket.Poll(int microseconds, SelectMode mode) allows to block until data is available or timeout occurs
Blocking is not always bad 
•Timeouts between 0 and 2% 
•Scale by adding new servers
Or scale by adding less servers 
•Cassandra is not very good at deterministic low latencies 
•We switched to Aerospike, same number of QPS, 2x less servers, p99% for reads <= 10 ms 
•The whole story here: “Married to Cassandra” http://vimeo.com/101290545
Takeaways 
•Don’t measure latency averages 
•It’s expensive to scale in .NET: 
•No decent Cassandra library, have to roll your own (while Java devs having fun with astyanax, datastax driver, etc.) 
•Even though we have rewritten our WCF based bidder to HttpListener (saved 10% CPU), netty throughput is 15% better 
•Finagle is a great framework
Takeaways 
•Blocking is not always bad, measure 
•Choose the right NoSQL(s) for the job
Thank you!

Mais conteúdo relacionado

Mais procurados

Advanced off heap ipc
Advanced off heap ipcAdvanced off heap ipc
Advanced off heap ipc
Peter Lawrey
 

Mais procurados (20)

Kafka At Scale in the Cloud
Kafka At Scale in the CloudKafka At Scale in the Cloud
Kafka At Scale in the Cloud
 
GC free coding in @Java presented @Geecon
GC free coding in @Java presented @GeeconGC free coding in @Java presented @Geecon
GC free coding in @Java presented @Geecon
 
Exactly-once Semantics in Apache Kafka
Exactly-once Semantics in Apache KafkaExactly-once Semantics in Apache Kafka
Exactly-once Semantics in Apache Kafka
 
Determinism in finance
Determinism in financeDeterminism in finance
Determinism in finance
 
Low latency in java 8 v5
Low latency in java 8 v5Low latency in java 8 v5
Low latency in java 8 v5
 
PlayStation and Searchable Cassandra Without Solr (Dustin Pham & Alexander Fi...
PlayStation and Searchable Cassandra Without Solr (Dustin Pham & Alexander Fi...PlayStation and Searchable Cassandra Without Solr (Dustin Pham & Alexander Fi...
PlayStation and Searchable Cassandra Without Solr (Dustin Pham & Alexander Fi...
 
Introduction to OpenHFT for Melbourne Java Users Group
Introduction to OpenHFT for Melbourne Java Users GroupIntroduction to OpenHFT for Melbourne Java Users Group
Introduction to OpenHFT for Melbourne Java Users Group
 
Writing and testing high frequency trading engines in java
Writing and testing high frequency trading engines in javaWriting and testing high frequency trading engines in java
Writing and testing high frequency trading engines in java
 
High Frequency Trading and NoSQL database
High Frequency Trading and NoSQL databaseHigh Frequency Trading and NoSQL database
High Frequency Trading and NoSQL database
 
Advanced off heap ipc
Advanced off heap ipcAdvanced off heap ipc
Advanced off heap ipc
 
The Good, The Bad, and The Avro (Graham Stirling, Saxo Bank and David Navalho...
The Good, The Bad, and The Avro (Graham Stirling, Saxo Bank and David Navalho...The Good, The Bad, and The Avro (Graham Stirling, Saxo Bank and David Navalho...
The Good, The Bad, and The Avro (Graham Stirling, Saxo Bank and David Navalho...
 
Nyc kafka meetup 2015 - when bad things happen to good kafka clusters
Nyc kafka meetup 2015 - when bad things happen to good kafka clustersNyc kafka meetup 2015 - when bad things happen to good kafka clusters
Nyc kafka meetup 2015 - when bad things happen to good kafka clusters
 
NGINX for Application Delivery & Acceleration
NGINX for Application Delivery & AccelerationNGINX for Application Delivery & Acceleration
NGINX for Application Delivery & Acceleration
 
Low latency microservices in java QCon New York 2016
Low latency microservices in java   QCon New York 2016Low latency microservices in java   QCon New York 2016
Low latency microservices in java QCon New York 2016
 
Reliability Guarantees for Apache Kafka
Reliability Guarantees for Apache KafkaReliability Guarantees for Apache Kafka
Reliability Guarantees for Apache Kafka
 
Disaster Recovery Plans for Apache Kafka
Disaster Recovery Plans for Apache KafkaDisaster Recovery Plans for Apache Kafka
Disaster Recovery Plans for Apache Kafka
 
Stream or segment : what is the best way to access your events in Pulsar_Neng
Stream or segment : what is the best way to access your events in Pulsar_NengStream or segment : what is the best way to access your events in Pulsar_Neng
Stream or segment : what is the best way to access your events in Pulsar_Neng
 
Data integration with rabbit mq and celery
Data integration with rabbit mq and celeryData integration with rabbit mq and celery
Data integration with rabbit mq and celery
 
Apache con2016final
Apache con2016final Apache con2016final
Apache con2016final
 
Low latency stream processing with jet
Low latency stream processing with jetLow latency stream processing with jet
Low latency stream processing with jet
 

Destaque

Николай Сивко "Хорошо поддерживаемое в продакшне приложение"
Николай Сивко "Хорошо поддерживаемое в продакшне приложение"Николай Сивко "Хорошо поддерживаемое в продакшне приложение"
Николай Сивко "Хорошо поддерживаемое в продакшне приложение"
Tanya Denisyuk
 
Андрей Дроздов "Создание высокопроизводительных rest api на tarantool"
Андрей Дроздов "Создание высокопроизводительных rest api на tarantool"Андрей Дроздов "Создание высокопроизводительных rest api на tarantool"
Андрей Дроздов "Создание высокопроизводительных rest api на tarantool"
Tanya Denisyuk
 
Алексей Лесовский "Тюнинг Linux для баз данных. "
Алексей Лесовский "Тюнинг Linux для баз данных. "Алексей Лесовский "Тюнинг Linux для баз данных. "
Алексей Лесовский "Тюнинг Linux для баз данных. "
Tanya Denisyuk
 

Destaque (20)

Сергей Сверчков "Want to build a secure private cloud for IoT with high avail...
Сергей Сверчков "Want to build a secure private cloud for IoT with high avail...Сергей Сверчков "Want to build a secure private cloud for IoT with high avail...
Сергей Сверчков "Want to build a secure private cloud for IoT with high avail...
 
Антон Тюрин, Евгений Сафронов, Инфраструктура под Cocaine
Антон Тюрин, Евгений Сафронов, Инфраструктура под CocaineАнтон Тюрин, Евгений Сафронов, Инфраструктура под Cocaine
Антон Тюрин, Евгений Сафронов, Инфраструктура под Cocaine
 
Артем Маринов "Сегментируем 600 млн. пользователей в режиме реального времени...
Артем Маринов "Сегментируем 600 млн. пользователей в режиме реального времени...Артем Маринов "Сегментируем 600 млн. пользователей в режиме реального времени...
Артем Маринов "Сегментируем 600 млн. пользователей в режиме реального времени...
 
Александр Тоболь, Кадры решают все, или стриминг видео в Одноклассниках
Александр Тоболь, Кадры решают все, или стриминг видео в ОдноклассникахАлександр Тоболь, Кадры решают все, или стриминг видео в Одноклассниках
Александр Тоболь, Кадры решают все, или стриминг видео в Одноклассниках
 
Alvaro Videla, Building a Distributed Data Ingestion System with RabbitMQ
Alvaro Videla, Building a Distributed Data Ingestion System with RabbitMQAlvaro Videla, Building a Distributed Data Ingestion System with RabbitMQ
Alvaro Videla, Building a Distributed Data Ingestion System with RabbitMQ
 
Кирилл Алешин, Ламбда Архитектура на практике
Кирилл Алешин, Ламбда Архитектура на практикеКирилл Алешин, Ламбда Архитектура на практике
Кирилл Алешин, Ламбда Архитектура на практике
 
Михаил Табунов, Аналитическая платформа на несколько миллиардов событий в месяц
Михаил Табунов, Аналитическая платформа на несколько миллиардов событий в месяцМихаил Табунов, Аналитическая платформа на несколько миллиардов событий в месяц
Михаил Табунов, Аналитическая платформа на несколько миллиардов событий в месяц
 
Сергей Аверин "Распространенные ошибки применения баз данных"
Сергей Аверин "Распространенные ошибки применения баз данных"Сергей Аверин "Распространенные ошибки применения баз данных"
Сергей Аверин "Распространенные ошибки применения баз данных"
 
Сергей Аверин, То, что вы хотели знать о HandlerSocket, но не смогли нагуглить
Сергей Аверин, То, что вы хотели знать о HandlerSocket, но не смогли нагуглитьСергей Аверин, То, что вы хотели знать о HandlerSocket, но не смогли нагуглить
Сергей Аверин, То, что вы хотели знать о HandlerSocket, но не смогли нагуглить
 
Максим Барышников, Что такое типовые проблемы нагруженных проектов и как их р...
Максим Барышников, Что такое типовые проблемы нагруженных проектов и как их р...Максим Барышников, Что такое типовые проблемы нагруженных проектов и как их р...
Максим Барышников, Что такое типовые проблемы нагруженных проектов и как их р...
 
Антон Щербаков, Отказоустойчивость на примере aviasales — почему даже если на...
Антон Щербаков, Отказоустойчивость на примере aviasales — почему даже если на...Антон Щербаков, Отказоустойчивость на примере aviasales — почему даже если на...
Антон Щербаков, Отказоустойчивость на примере aviasales — почему даже если на...
 
Николай Сивко "Хорошо поддерживаемое в продакшне приложение"
Николай Сивко "Хорошо поддерживаемое в продакшне приложение"Николай Сивко "Хорошо поддерживаемое в продакшне приложение"
Николай Сивко "Хорошо поддерживаемое в продакшне приложение"
 
Борис Тверитнев, Воздержание как практика программирования
Борис Тверитнев, Воздержание как практика программированияБорис Тверитнев, Воздержание как практика программирования
Борис Тверитнев, Воздержание как практика программирования
 
Денис Колошко, Пример нагруженной системы на базе продуктов Microsoft, Amazon...
Денис Колошко, Пример нагруженной системы на базе продуктов Microsoft, Amazon...Денис Колошко, Пример нагруженной системы на базе продуктов Microsoft, Amazon...
Денис Колошко, Пример нагруженной системы на базе продуктов Microsoft, Amazon...
 
Андрей Дроздов "Создание высокопроизводительных rest api на tarantool"
Андрей Дроздов "Создание высокопроизводительных rest api на tarantool"Андрей Дроздов "Создание высокопроизводительных rest api на tarantool"
Андрей Дроздов "Создание высокопроизводительных rest api на tarantool"
 
Денис Баталов, Принципы построения высоконагруженных сайтов на платформе АWS
Денис Баталов, Принципы построения высоконагруженных сайтов на платформе АWSДенис Баталов, Принципы построения высоконагруженных сайтов на платформе АWS
Денис Баталов, Принципы построения высоконагруженных сайтов на платформе АWS
 
Дмитрий Хоревич "Cloud native security with UAA \ Как защитить микросервисы с...
Дмитрий Хоревич "Cloud native security with UAA \ Как защитить микросервисы с...Дмитрий Хоревич "Cloud native security with UAA \ Как защитить микросервисы с...
Дмитрий Хоревич "Cloud native security with UAA \ Как защитить микросервисы с...
 
Артем Гавриченков "The Dark Side of Things: Distributed Denial of Service Att...
Артем Гавриченков "The Dark Side of Things: Distributed Denial of Service Att...Артем Гавриченков "The Dark Side of Things: Distributed Denial of Service Att...
Артем Гавриченков "The Dark Side of Things: Distributed Denial of Service Att...
 
Александр Краковецкий "Разработка интеллектуальных ботов с помощью Microsoft ...
Александр Краковецкий "Разработка интеллектуальных ботов с помощью Microsoft ...Александр Краковецкий "Разработка интеллектуальных ботов с помощью Microsoft ...
Александр Краковецкий "Разработка интеллектуальных ботов с помощью Microsoft ...
 
Алексей Лесовский "Тюнинг Linux для баз данных. "
Алексей Лесовский "Тюнинг Linux для баз данных. "Алексей Лесовский "Тюнинг Linux для баз данных. "
Алексей Лесовский "Тюнинг Linux для баз данных. "
 

Semelhante a Donatas Mažionis, Building low latency web APIs

Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
xlight
 
M6d cassandrapresentation
M6d cassandrapresentationM6d cassandrapresentation
M6d cassandrapresentation
Edward Capriolo
 
Redis Everywhere - Sunshine PHP
Redis Everywhere - Sunshine PHPRedis Everywhere - Sunshine PHP
Redis Everywhere - Sunshine PHP
Ricard Clau
 
RedisConf18 - Techniques for Synchronizing In-Memory Caches with Redis
RedisConf18 - Techniques for Synchronizing In-Memory Caches with RedisRedisConf18 - Techniques for Synchronizing In-Memory Caches with Redis
RedisConf18 - Techniques for Synchronizing In-Memory Caches with Redis
Redis Labs
 
Sizing MongoDB on AWS with Wired Tiger-Patrick and Vigyan-Final
Sizing MongoDB on AWS with Wired Tiger-Patrick and Vigyan-FinalSizing MongoDB on AWS with Wired Tiger-Patrick and Vigyan-Final
Sizing MongoDB on AWS with Wired Tiger-Patrick and Vigyan-Final
Vigyan Jain
 

Semelhante a Donatas Mažionis, Building low latency web APIs (20)

Fixing twitter
Fixing twitterFixing twitter
Fixing twitter
 
Fixing_Twitter
Fixing_TwitterFixing_Twitter
Fixing_Twitter
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
 
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...Fixing Twitter  Improving The Performance And Scalability Of The Worlds Most ...
Fixing Twitter Improving The Performance And Scalability Of The Worlds Most ...
 
M6d cassandrapresentation
M6d cassandrapresentationM6d cassandrapresentation
M6d cassandrapresentation
 
What's inside the black box? Using ML to tune and manage Kafka. (Matthew Stum...
What's inside the black box? Using ML to tune and manage Kafka. (Matthew Stum...What's inside the black box? Using ML to tune and manage Kafka. (Matthew Stum...
What's inside the black box? Using ML to tune and manage Kafka. (Matthew Stum...
 
Redis Everywhere - Sunshine PHP
Redis Everywhere - Sunshine PHPRedis Everywhere - Sunshine PHP
Redis Everywhere - Sunshine PHP
 
RedisConf18 - Techniques for Synchronizing In-Memory Caches with Redis
RedisConf18 - Techniques for Synchronizing In-Memory Caches with RedisRedisConf18 - Techniques for Synchronizing In-Memory Caches with Redis
RedisConf18 - Techniques for Synchronizing In-Memory Caches with Redis
 
Sizing MongoDB on AWS with Wired Tiger-Patrick and Vigyan-Final
Sizing MongoDB on AWS with Wired Tiger-Patrick and Vigyan-FinalSizing MongoDB on AWS with Wired Tiger-Patrick and Vigyan-Final
Sizing MongoDB on AWS with Wired Tiger-Patrick and Vigyan-Final
 
Getting Started with Amazon Redshift
Getting Started with Amazon RedshiftGetting Started with Amazon Redshift
Getting Started with Amazon Redshift
 
Getting Started with Amazon Redshift
Getting Started with Amazon RedshiftGetting Started with Amazon Redshift
Getting Started with Amazon Redshift
 
Realtime Analytics on AWS
Realtime Analytics on AWSRealtime Analytics on AWS
Realtime Analytics on AWS
 
High Performance Object Pascal Code on Servers (at EKON 22)
High Performance Object Pascal Code on Servers (at EKON 22)High Performance Object Pascal Code on Servers (at EKON 22)
High Performance Object Pascal Code on Servers (at EKON 22)
 
Select Stars: A SQL DBA's Introduction to Azure Cosmos DB (SQL Saturday Orego...
Select Stars: A SQL DBA's Introduction to Azure Cosmos DB (SQL Saturday Orego...Select Stars: A SQL DBA's Introduction to Azure Cosmos DB (SQL Saturday Orego...
Select Stars: A SQL DBA's Introduction to Azure Cosmos DB (SQL Saturday Orego...
 
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
AWS re:Invent 2016: Amazon CloudFront Flash Talks: Best Practices on Configur...
 
Hyperbatch (LoteRapido) - Punta Dreamin' 2017
Hyperbatch (LoteRapido) - Punta Dreamin' 2017Hyperbatch (LoteRapido) - Punta Dreamin' 2017
Hyperbatch (LoteRapido) - Punta Dreamin' 2017
 
Zero ETL analytics with LLAP in Azure HDInsight
Zero ETL analytics with LLAP in Azure HDInsightZero ETL analytics with LLAP in Azure HDInsight
Zero ETL analytics with LLAP in Azure HDInsight
 
Data Pipelines with Spark & DataStax Enterprise
Data Pipelines with Spark & DataStax EnterpriseData Pipelines with Spark & DataStax Enterprise
Data Pipelines with Spark & DataStax Enterprise
 
Aerospike & GCE (LSPE Talk)
Aerospike & GCE (LSPE Talk)Aerospike & GCE (LSPE Talk)
Aerospike & GCE (LSPE Talk)
 
AWS Webcast - Managing Big Data in the AWS Cloud_20140924
AWS Webcast - Managing Big Data in the AWS Cloud_20140924AWS Webcast - Managing Big Data in the AWS Cloud_20140924
AWS Webcast - Managing Big Data in the AWS Cloud_20140924
 

Mais de Tanya Denisyuk

Алексей Залесов-«Управление контейнерами в облаках»
Алексей Залесов-«Управление контейнерами в облаках»Алексей Залесов-«Управление контейнерами в облаках»
Алексей Залесов-«Управление контейнерами в облаках»
Tanya Denisyuk
 
Юрий Насретдинов-«Сбор логов в «облаке» в Badoo»
Юрий Насретдинов-«Сбор логов в «облаке» в Badoo»Юрий Насретдинов-«Сбор логов в «облаке» в Badoo»
Юрий Насретдинов-«Сбор логов в «облаке» в Badoo»
Tanya Denisyuk
 
Дмитрий Лазаренко-«Живая миграция и отказоустойчивость контейнеров в гибридно...
Дмитрий Лазаренко-«Живая миграция и отказоустойчивость контейнеров в гибридно...Дмитрий Лазаренко-«Живая миграция и отказоустойчивость контейнеров в гибридно...
Дмитрий Лазаренко-«Живая миграция и отказоустойчивость контейнеров в гибридно...
Tanya Denisyuk
 
Роман Иманкулов-«Быстрые и масштабируемые приложения с Sync API»
Роман Иманкулов-«Быстрые и масштабируемые приложения с Sync API»Роман Иманкулов-«Быстрые и масштабируемые приложения с Sync API»
Роман Иманкулов-«Быстрые и масштабируемые приложения с Sync API»
Tanya Denisyuk
 
Дмитрий Дурасов-«Технологии контейнеризации в Windows Server 2016»
Дмитрий Дурасов-«Технологии контейнеризации в Windows Server 2016»Дмитрий Дурасов-«Технологии контейнеризации в Windows Server 2016»
Дмитрий Дурасов-«Технологии контейнеризации в Windows Server 2016»
Tanya Denisyuk
 

Mais de Tanya Denisyuk (15)

Артем Маринов "Сегментируем 600 млн. пользователей в режиме реального времени...
Артем Маринов "Сегментируем 600 млн. пользователей в режиме реального времени...Артем Маринов "Сегментируем 600 млн. пользователей в режиме реального времени...
Артем Маринов "Сегментируем 600 млн. пользователей в режиме реального времени...
 
Вадим Мадисон "Опыт разработки через микросервисы"
Вадим Мадисон "Опыт разработки через микросервисы"Вадим Мадисон "Опыт разработки через микросервисы"
Вадим Мадисон "Опыт разработки через микросервисы"
 
Левон Авакян "Архитектура мета игры Wargaming. Глобальная карта 2.0"
Левон  Авакян "Архитектура мета игры Wargaming. Глобальная карта 2.0"Левон  Авакян "Архитектура мета игры Wargaming. Глобальная карта 2.0"
Левон Авакян "Архитектура мета игры Wargaming. Глобальная карта 2.0"
 
Андрей Светлов-«Делаем своё решение для оптимальной загрузки кластера»
Андрей Светлов-«Делаем своё решение для оптимальной загрузки кластера»Андрей Светлов-«Делаем своё решение для оптимальной загрузки кластера»
Андрей Светлов-«Делаем своё решение для оптимальной загрузки кластера»
 
Александр Ломов-«Как перестать беспокоиться и начать использовать Cloud Foundry»
Александр Ломов-«Как перестать беспокоиться и начать использовать Cloud Foundry»Александр Ломов-«Как перестать беспокоиться и начать использовать Cloud Foundry»
Александр Ломов-«Как перестать беспокоиться и начать использовать Cloud Foundry»
 
Алексей Залесов-«Управление контейнерами в облаках»
Алексей Залесов-«Управление контейнерами в облаках»Алексей Залесов-«Управление контейнерами в облаках»
Алексей Залесов-«Управление контейнерами в облаках»
 
Максим Барышиков-«WoT: Geographically distributed cluster of clusters»
Максим Барышиков-«WoT: Geographically distributed cluster of clusters»Максим Барышиков-«WoT: Geographically distributed cluster of clusters»
Максим Барышиков-«WoT: Geographically distributed cluster of clusters»
 
Левон Авакян-«Эволюция кланов в Wargaming. От веб страницы на танковом портал...
Левон Авакян-«Эволюция кланов в Wargaming. От веб страницы на танковом портал...Левон Авакян-«Эволюция кланов в Wargaming. От веб страницы на танковом портал...
Левон Авакян-«Эволюция кланов в Wargaming. От веб страницы на танковом портал...
 
Юрий Насретдинов-«Сбор логов в «облаке» в Badoo»
Юрий Насретдинов-«Сбор логов в «облаке» в Badoo»Юрий Насретдинов-«Сбор логов в «облаке» в Badoo»
Юрий Насретдинов-«Сбор логов в «облаке» в Badoo»
 
Павел Вейник-«Программирование и лингвистика: как понять язык и как извлечь з...
Павел Вейник-«Программирование и лингвистика: как понять язык и как извлечь з...Павел Вейник-«Программирование и лингвистика: как понять язык и как извлечь з...
Павел Вейник-«Программирование и лингвистика: как понять язык и как извлечь з...
 
Михаил Серченя-«Построение отказоустойчивой масштабируемой среды для WEB и бе...
Михаил Серченя-«Построение отказоустойчивой масштабируемой среды для WEB и бе...Михаил Серченя-«Построение отказоустойчивой масштабируемой среды для WEB и бе...
Михаил Серченя-«Построение отказоустойчивой масштабируемой среды для WEB и бе...
 
Дмитрий Лазаренко-«Живая миграция и отказоустойчивость контейнеров в гибридно...
Дмитрий Лазаренко-«Живая миграция и отказоустойчивость контейнеров в гибридно...Дмитрий Лазаренко-«Живая миграция и отказоустойчивость контейнеров в гибридно...
Дмитрий Лазаренко-«Живая миграция и отказоустойчивость контейнеров в гибридно...
 
Андрей Федоренчик- «Высоконагруженная система с аналитикой на InfoBright»
Андрей Федоренчик- «Высоконагруженная система с аналитикой на InfoBright»Андрей Федоренчик- «Высоконагруженная система с аналитикой на InfoBright»
Андрей Федоренчик- «Высоконагруженная система с аналитикой на InfoBright»
 
Роман Иманкулов-«Быстрые и масштабируемые приложения с Sync API»
Роман Иманкулов-«Быстрые и масштабируемые приложения с Sync API»Роман Иманкулов-«Быстрые и масштабируемые приложения с Sync API»
Роман Иманкулов-«Быстрые и масштабируемые приложения с Sync API»
 
Дмитрий Дурасов-«Технологии контейнеризации в Windows Server 2016»
Дмитрий Дурасов-«Технологии контейнеризации в Windows Server 2016»Дмитрий Дурасов-«Технологии контейнеризации в Windows Server 2016»
Дмитрий Дурасов-«Технологии контейнеризации в Windows Server 2016»
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Último (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

Donatas Mažionis, Building low latency web APIs

  • 1.
  • 2. This talk is not a hardcore latency talk I will not talk about: •CPU caches •System.nanoTime •lockless concurrent queues •magic low latency framework
  • 3. This talk is not a hardcore latency talk Scaling from 500 to 150K QPS, the hard way
  • 4. Latency a size telling us how long something took
  • 6. Why average is a common metric? •Everyone understands it •It’s easy to calculate
  • 7. Why average is a common metric? •Everyone understands it •It’s easy to calculate •It can also hide important unwanted behaviour of the system!
  • 8. Imagine we have a service with the following response latencies
  • 10. Calculating latency average 20% of the requests got latency twice as above 10 ms
  • 11. Percentiles The value below which a given percentage of observations in a group of observations fall Like p50% = the max value of 50% of the values
  • 14. Libraries for tracking latencies HdrHistogram: http://hdrhistogram.github.io/HdrHistogram/ Uses fixed memory and constant CPU for recording (C, Java, C# work in progress). Finagle: https://twitter.github.io/finagle/ Scala, Java RPC framework by Twitter, has built in stats and latency tracking.
  • 15. APIs in online advertising
  • 16. APIs in online advertising 98% of requests under 100 ms
  • 17. APIs in online advertising 98% of requests under 100 ms HTTP
  • 18. APIs in online advertising 98% of requests under 100 ms HTTP JSON
  • 19. APIs in online advertising 98% of requests under 100 ms HTTP JSON Protocol Buffers
  • 20. Real-time bidding API How much would you pay if you give us an ad of size 200x120 to show it on youtube.com for a user from Belgium, who is interested in Sports and Culture?
  • 22.
  • 23. 1.Deserialize request 2.Process some rules 3.Get pre-calculated bid price from storage 4.Calculate some more 5.Serialize response Real-time bidding request processing All rest 40 ms for network latency 40 ms 60 ms
  • 24. LVS + keepalived Profiler API User profiles Bid price calculators Bidder API Ad serving
  • 25. Redis in 50 words or less Redis is an open source, BSD licensed, advanced key-value cache and store.
  • 26. Redis as key-value store •Append write, flush every second •Operations on multiple keys •Works great, but watch out when writing/reading on the same node simultaneously
  • 27. Redis latencies Simultaneous writes and reads on the same node
  • 28. Cassandra in 50 words or less Apache Cassandra is an open source, distributed, decentralized, elastically scalable, highly available, fault-tolerant, tuneably consistent, column-oriented database
  • 29. Why Cassandra is good •Fast writes •User profile is a natural key-value model •Easy to scale (especially with virtual nodes) •Seemed the most mature at that time (started using from v0.7) •Runs on a legacy spare HW •Runs on Windows :)
  • 30. Why Cassandra is good •Fast writes •User profile is a natural key-value model •All nice features mentioned before •Seemed the most mature at that time (started using from v0.7) •Runs on a legacy spare HW •Runs on Windows :)
  • 31. Why Cassandra is not so good
  • 32. Why Cassandra is not so good GC pauses
  • 33. Cassandra tuning tricks that worked •LeveledCompactionStrategy •Changing Java heap size (8 GB) •Client direct read of data (token aware strategy)
  • 34.
  • 35. Cassandra tuning tricks that did not work GC tuning
  • 36. Cassandra tuning tricks that did not work GC tuning 20% of requests exceeding 40 ms
  • 37. Connecting to Cassandra Thrift version
  • 38. Fail fast plan 1.Set a TSocket timeout to 10 ms 2.If node does not answer under 10 ms, try another from the same range 3.Repeat this 3 times
  • 39. Timeouts in .NET are broken •.NET Socket SendReceiveTimeout does not work for values less than 500 ms •Same applies to SocketAsyncEventArgs •Async version even worse (timer queues, etc.)
  • 40. Thing that worked Socket.Poll(int microseconds, SelectMode mode) allows to block until data is available or timeout occurs
  • 41. Blocking is not always bad •Timeouts between 0 and 2% •Scale by adding new servers
  • 42. Or scale by adding less servers •Cassandra is not very good at deterministic low latencies •We switched to Aerospike, same number of QPS, 2x less servers, p99% for reads <= 10 ms •The whole story here: “Married to Cassandra” http://vimeo.com/101290545
  • 43. Takeaways •Don’t measure latency averages •It’s expensive to scale in .NET: •No decent Cassandra library, have to roll your own (while Java devs having fun with astyanax, datastax driver, etc.) •Even though we have rewritten our WCF based bidder to HttpListener (saved 10% CPU), netty throughput is 15% better •Finagle is a great framework
  • 44. Takeaways •Blocking is not always bad, measure •Choose the right NoSQL(s) for the job