Story of architecture evolution of one project from zero to Lambda Architecture. Also includes information on how we scaled cluster as soon as architecture is set up.
Contains nice performance charts after every architecture change.
7. Service designed to offload highly
concurrent scenario of live voting
• User puts a vote
• User requests results on campaign
• Manager requests reports on campaigns
• Admin controls the system
13. Benchmark it!
• Simple throughout scenario:
user.vote()
user.request(results)
• Stop tests when error rate raises above 5%
• Benchmark tool runs locally, targeting could server
14. Gatling
• An open-source load testing framework based on
Scala, Akka and Netty
• High performance
• Out-of-box HTTP support
• Ready-to-present HTML reports
• Scenario recorder and developer-friendly DSL
http://gatling.io
21. Redis
• In-memory data structure store (set, map, etc)
• Easy leader board implementation
• HyperLogLog is its native data structure
http://redis.io
Робота над проектом триває, хоча останнім часом активність не велика.
Сервіс для підтримки високонавантаженого сценарію одночасного голосування
Software as a Service
Maria DB 5.5.44 (no second level cache in our persistence, all tests started with empty DB, connection pooling)
Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run".
Spring Data's mission is to provide a familiar and consistent, Spring-based programming model for data access while still retaining the special traits of the underlying data store.
MariaDB An enhanced, drop-in replacement for MySQL. MariaDB 5.5 is a stable (GA) release of MariaDB. It is MariaDB 5.3 + MySQL 5.5
Дає видимість руху, правильно, неправильно, і чи взагалі дало якусь зміну
1000 campaigns
15-100k votes
Коли позбулися 3-4 джойнів то система змогла витримувати більше навантаження, хоча продуктивність не збільшилася.
Флуктуації на графіку пов”язані з нестабільність віртаулок які нами викоистовувалися.
Бачимо, що система має явне обмеження по перформансу. З цим треба щось робити.
Звичайним в цій ситуації є буферизація запитів, тобто будемо ставити їх в чергу.
Черга — я з малими бавлюся в паттерн черга — я складаю іграшки на коврик, а вони їх з коврика сортують по ящиках ))
Ми знаємо про круту технологію, зараз популярна…
Є чудова презентація від Колі Аліменкова з цьогорічного ЖЕЕКонфа
A single Kafka broker can handle hundreds of megabytes of reads and writes per second from thousands of clients.
Kafka is designed to allow a single cluster to serve as the central data backbone for a large organization. It can be elastically and transparently expanded without downtime. Data streams are partitioned and spread over a cluster of machines to allow data streams larger than the capability of any single machine and to allow clusters of co-ordinated consumers
Messages are persisted on disk and replicated within the cluster to prevent data loss. Each broker can handle terabytes of messages without performance impact.
Kafka has a modern cluster-centric design that offers strong durability and fault-tolerance guarantees.
Kafka 0.8.2.1 (Scala 2.9.1, only one partition)
Система стала асинхронна, варто було б міряти також лейтенсі. Тримаємо це в секреті ) Хто зауважить — тому подарунок
1.5 - 2.1x
Це вже добряче швидко, але зараз ми роздаємо дані з диска.
Обрахунки виконуються в запитах до бази даних які досить часто не є найшвидні і не скейляться.
Якщо роздавати дані з памяті це дасть нам приріст продуктивності…
Вибрали бо ориганільно розраховували на використання лідербордів.
З реального використання можна взяти HyperLogLog як ефективний приблизний підрахунок голосів по компанії
In the Redis implementation it only uses 12kbytes per key to count with a standard error of 0.81%, and there is no limit to the number of items you can count, unless you approach 2^64 items (which seems quite unlikely).
// key == set
~1.6x performance boost
Але є обмеження на алгоритми по створенню репортів:
було б добре мати якісь загальний інструмент для їх реалізації
Про спарк є дуже добра презентація від Тараса, якщо ви її не чули — рекомендую подивитися відео на сайті морнинга.
Spark has an advanced DAG execution engine that supports cyclic data flow and in-memory computing.
Spark offers over 80 high-level operators that make it easy to build parallel apps. And you can use it interactively from the Scala, Python and R shells.
Spark powers a stack of libraries including SQL and DataFrames, MLlib for machine learning, GraphX, and Spark Streaming. You can combine these libraries seamlessly in the same application.
You can run Spark using its standalone cluster mode, on EC2, on Hadoop YARN, or on Apache Mesos. Access data in HDFS, Cassandra, HBase, Hive, Tachyon, and any Hadoop data source.
Основна мета цього кроку — екстенсібіліті системи по відношенню до алгоритмів обробки даних.
Також на live layer можна було б використати Spark Streaming, як узагальненя інкрементальних обрахунків. Можливо це буде реалізовано на одному з наступних етапів.
Додавання ще одного розподіленого компонента швидше за все не дасть приросту продуктивності, на цьому етапі заміри лейтенсі яке ми міряли
Обмеженням системи на даному етапі стає можливість збереження великого об”єму даних: хоч до сих пір база даних справлялася з цією роботою, але вона не найкращий кандидат.
Є старенька всім відома технологія… але про це за декілька слайдів.
Зараз іде робота над заміною маріяДБ на HDFS.
Отже ми прийшли до картинки із остаточним варіантом архітектури.
Дані вливаються великим потоком
Можемо зберігати великі масиви даних
Можем опрацьовувати великі масиви даних
Є можливість швидкої відповіді на ряд поставлених питань, більш складні питання можна обрахувати точно з певною затримкою
Кажуть в тої архітектури є вже назва.
ВИБОРИ В УКРАЇНІ:
бюлетні == all_data
ЦВК == batch_view
екзитпол == realtime_view
Hadoop
The batch layer precomputes results using a distributed processing system that can handle very large quantities of data. The batch layer aims at perfect accuracy by being able to process all available data when generating views. This means it can fix any errors by recomputing based on the complete data set, then updating existing views. Output is typically stored in a read-only database, with updates completely replacing existing precomputed views.
Apache Hadoop is the de facto standard batch-processing system used in most high-throughput architectures.
Simple
Robust
Predictable
Easy to configure and operate
Cassandra/HBase/ElaphantDB, також може бути Hive/Impala
Output from the batch and speed layers are stored in the serving layer, which responds to ad-hoc queries by returning precomputed views or building views from the processed data.
Examples of technologies used in the serving layer include Druid, which provides a single cluster to handle output from both layers. Dedicated stores used in the serving layer include Apache Cassandra or Apache HBase for speed-layer output, and Elephant DB or Cloudera Impala for batch-layer output.
Але чогось не вистарчає…
Complexity isolation — complexity is pushed to layer whose results are temporary .
Eventual accuracy — eventually all the results will be taken from serving layer.
Speed layer might use approximate algorithms like HyperLogLog and BloomFilters for computations.
Storm/Spark Streaming
The speed layer processes data streams in real time and without the requirements of fix-ups or completeness. This layer sacrifices throughput as it aims to minimize latency by providing real-time views into the most recent data. Essentially, the speed layer is responsible for filling the "gap" caused by the batch layer's lag in providing views based on the most recent data. This layer's views may not be as accurate or complete as the ones eventually produced by the batch layer, but they are available almost immediately after data is received, and can be replaced when the batch layer's views for the same data become available.
Stream-processing technologies typically used in this layer include Apache Storm, SQLstream and Apache Spark. Output is typically stored on fast NoSQL databases.
Бачило що маємо певний ліміт по навантаженню, спільний для всіх варіантів. Мабуть це томкет ) Хто дасть такий варіант — подарунок.
Система тепер досить добре витримує наватнаження. Цікавим є закономірний спад в околі 12к…
Ubuntu 14.04 (virtual machines, 2 cores, 8 GB RAM)
згадати про Haproxy vs nginx
Згадати про обмеження в 12к для всіх тестів, це був томкет. Треба оптимізувати.
Стовпчики
Скейлінг фактор!!!
Як це типово для високонагружених рішень, я очікував що вульким місцем стане збереження даних або їх обробка, наприклад перша моя задача була — давай зробимо так щоб Кафка стала вузьким місцем, але вепрлися в лоад балансер. Та й 30к RPS це нормальна нагрузка.