Quite often the architecture in JavaScript reduces itself to the choice of a framework according to the frontend world’s recent trends. What if we told you that the choice of technology is just the step №7 on your way to developing project design? Every day many projects feel the draught or even fall to pieces because of the incorrectly chosen architecture.
We’ll share some stories that can help you look at the architecture and its meaning for the modern apps from the right perspective, as well as avoid mistakes that can simply ruin your project.
42. Functional Requirements
“If only the functionality would matter then we would need no
internal structure, a single monolithic blob would be enough.”
Software Architecture in Practice
62. Architecture
PRG Datacenter
Prod environment
PRODUCTION
CBJ Datacenter
Prod environment
PRODUCTION
“PLAY” Server Host 2
eWF Backend
(Play port 9000)
“ADT” Server
ADT Backend
(Play port 9000)
CAS
(Tomcat port
8080)
“Balancer” Server
NGinx
Frontend
NGinx
Backend
EWF->ADT: Get CI values
EWF->CAS: Authenticate
EWF->CAS: Get new tokenCalls from external systems
“Report” Server
Reporting server
EWF->Report: schedule a report
EWF-Report: generate report
ReplicationeWF
Prod
ADT
Prod
CAS
Prod
“CQ Author” Server
“CQ Publisher” Server
CQ Dispatcher
CQ Publisher
(Prod run mode)
CQ Author
(Passive)
Static resources
F5
BIG IP
Enduser
eWF
Prod
ADT
Prod
CAS
Prod
F5
BIG IP
eWF
Staging
ADT
Staging
CAS
Staging
Replication
Staging (Prod Config)
“PLAY” Server
eWF Backend
(Play 9000)
uses local cache
“ADT” Server
ADT Backend
(Play)
uses local cache
CAS
(Tomcat)
“Balancer” Server
NGinx
Frontend
NGinx
Backend
EWF->ADT: Get CI values
Reporting server
“CQ Publisher” Server
CQ Dispatcher
CQ Publisher
(Staging run mode)
“Centr. logging” Server
Centr.
Logging
server
Mongo
DB
“PLAY” Server Host 1
eWF Backend
(Play port 9000)
TSA
(main)
Cluster
TSA
(backup
host 2)
TSA
(main)
TSA
(backup
host 2)
REST calls from UI
3dns
Akamai
“PLAY” Server Host 2
eWF Backend
(Play port 9000)
“ADT” Server
ADT Backend
(Play port 9000)
CAS
(Tomcat port
8080)
“Balancer” Server
NGinx
Frontend
NGinx
Backend
EWF->ADT: Get CI values
EWF->CAS: Authenticate
EWF->CAS: Get new tokenCalls from external systems
“Report” Server
Reporting server
EWF->Report: schedule a report
EWF-Report: generate report
“CQ Author” Server
“CQ Publisher” Server
CQ Dispatcher
CQ Publisher
(Prod run mode)
CQ Author
(Activee)
Static resources
“Centr. logging” Server
Centr.
Logging
server
Mongo
DB
“PLAY” Server Host 1
eWF Backend
(Play port 9000)
TSA
(main)
TSA
(backup
host 2)
TSA
(main)
TSA
(backup
host 2)
REST calls from UI
Cluster
Internal reports
External reports
E2E (UAT) environment
Same as Prod environment in PRG
CQ Authors
Support team
Manage content
DHl Admins
Manage configuration items
Run internal reports
Solve Online Problems
Release new version
UAT team
Publish conf items values
Report
Prod
Report
Prod
Legend
Application
Hardware service
High available hosts (at least 2 hosts)
Cluster
Single host
High availbale DB
Report
Prod
“Migratiion” Server
Migration Backend
Draft servers
Migration
Schema
Migration Users
Migrate existing data
Centr
logging
agent
Centr
logging
agent
Centr
logging
agent
Centr
logging
agent
Centr
logging
agent
Centr
logging
agent
Centr
logging
agent
Centr
logging
agent
Centr
logging
agent
Centr
logging
agent
Centr
logging
agent
Само понятие архитектуры у меня всегда ассоциируется со строениями
Уже традиционно, я хотел бы начать свое выступление с историиИстории, повествующей о шведском корабле(не побоюсь этого слова Галере) Ваза, который заставит вас совершенно по-другому взглянуть на подходы к построению архитектуры приложений и современную роль архитектора на проекте
70 meters long, able to carry 300 soldiers, and with an astonishing 64 heavy guns mounted on two gun decks
Hybertsson had to balance many concerns. Swift time to deployment was critical, but so were performance, functionality, safety, reliability, and cost. He was also responsible to a variety of stakeholders. In this case, the primary customer was the king, but Hybertsson also was responsible to the crew that would sail his creation. Also like all architects, Hybertsson brought his experience with him to the task. In this case, his experience told him to design the Vasa as though it were a single-gun-deck ship and then extrapolate, which was in accordance with the technical environment of the day. Faced with an impossible task, Hybertsson had the good sense to die about a year before the ship was finished.SA in Practice P-165
К воскресенью 10 1628 года «Ваза» стоял на швартовах напротив королевского дворца. Там на борт был принят балласт, а также пушки, порох и ядра для первого плавания.Когда корабль вышел на открытое пространство бухты, сильный порыв ветра наполнил паруса, и «Ваза» начал крениться на подветренную сторону, но затем выровнялся и прошёл ещё примерно 1300 метров, дойдя до острова Бекхольмен у входа в гавань Стокгольма. Там, в ста метрах от острова, новый порыв ветра снова накренил корабль, на этот раз значительно сильнее. Вода хлынула через открытые пушечные порты, корабль лёг на борт и начал тонуть с поднятыми парусами и развевающимися флагами.
Когда корабль вышел на открытое пространство бухты, сильный порыв ветра наполнил паруса, и «Ваза» начал крениться на подветренную сторону, но затем выровнялся и прошёл ещё примерно 1300 метров, дойдя до острова Бекхольмен у входа в гавань Стокгольма. Там, в ста метрах от острова, новый порыв ветра снова накренил корабль, на этот раз значительно сильнее. Вода хлынула через открытые пушечные порты, корабль лёг на борт и начал тонуть с поднятыми парусами и развевающимися флагами.
Никаких результатов не принесли допросы кораблестроителей, под руководством которых строился «Ваза». Основная сложность заключалась в том, что фактический строитель корабля Хенрик Хюбертссон умер за год до катастрофы. Ответственные за верфь, где был построен «Ваза», судостроитель Хейн Якобссон и арендатор верфи Арент де Грот поклялись в своей невиновности, указав, что корабль был построен по тем размерам, которые утвердил лично король Густав II Адольф. И на борту было то количество пушек, которое стояло в контракте.
Привлекать к следствию самого короля в Государственном совете не решились. В итоге никто не был признан виновным и никто не был осуждён за катастрофу.В ходе следствия выдвигались разнообразные гипотезы относительно причин гибели корабля: алкогольное опьянение капитана, ненадёжное закрепление пушек и т. д. Ни одна из этих версий не подтвердилась. В конце концов, следствием был сделан вывод: при проектировании корабля были допущены ошибки. Действительно, «Ваза» имел слишком высоко расположенный центр тяжести и был слишком узок, хотя судостроители, тайно от короля, увеличили его ширину на 2,5 метра, его подводная часть по отношению к корпусу, рангоуту и артиллерии имела слишком малый вес. Это привело к неустойчивости корабля. Капитан корабля Сёфринг Ханссен сам отмечал это на следствии, однако в случае с «Вазой» предпринять было нечего: взять большее количество балласта и тем повысить остойчивость корабля не позволяла его конструкция.
История Вазы, хотя более 375 лет, хорошо иллюстрирует Цикл влияния архитектуры: цели организации порождают требования, которые порождают архитектуру, которая порождает систему.И цена ошибки на любом из этапов может стоить вам корабль
При неверной архитектуре, сколько проектов мертвы еще до написания первой строчки кода?
Говоря об архитектуре, каждый смотрит на нее под своим углов со своей перспективы.Поставщики пушек смотрели на судно, как на объект, который должен был вместить ровно 64 пушкиМаляры – как на площадь для закраски
Король, как главный заказчик, смотрел на корабль как инвестицию в свое политическое будущееЧто в свою очередь дало толчок к созданию каких-то чертежейКорабль строился в верфях и доках
Сейчас казнить архитекторов нельзя (запрещает законодательство), а так бы книга была написана кровью
Во время историй, я буду предлагать решать архитектурные задачки или катыГде в упрощенном виде описан самый первый запрос, который может прийти от клиента.
История Вазы, хотя более 375 лет, хорошо иллюстрирует Цикл влияния архитектуры: цели организации порождают требования, которые порождают архитектуру, которая порождает систему.
Responsible (R): the persons who will be performing the work on the task.
Accountable (A): the person who is ultimately held accountable for successful completion of the task and is the decision maker.
Consulted (C): the stakeholders who will be asked to provide an opinion or information about the task.
Informed (I): a stakeholders that is kept up to date on the task and notified of its outcome.
Из Минусов RACI матрицы, что она не покрывает следующий случай
Кстати, вы с этим типом стейкхолдеров тоже встречались, например законы требующие получить сертификат соответствия у внешние аудиторских компаний по аксесабилити или безопасности вашего приложения.
Business goal was to be quicker then competitors
At the time of writing the spec competitors were doing transactions in 0.6 sec
A month later a new product was launched offering transactions in 0.4 sec
Заказчик хотел иметь самую быструю систему (самый большой самый тяжеловооруженный корабль), на это была направлена вся его рекламаА Ценность такой системы заметно падала!
Business Objective - A strategic business goal for an enterprise.
Example - We will provide the best customer service in our field.
Business Principle - High level rules that govern the manner in which business capabilities are delivered by the enterprise and provide the context for designing and defining how these capabilities will be realised.
Example - Quality will not be sacrificed by cost efficiency.
Business Domain - This is the top level construct in the Business Architecture. It provides a means of categorising the business related elements independent of the context in which it is applied. In other words the main groupings of the business, not necessarily the organisational functions. e.g., Invoicing belongs to the Finance domain but may appear in the Sales Order process.
Example - Sales and Marketing, Operations, Customer Services, Finance, Fulfilment, HR, IT, Business Control, Trading and Order Management.
Business Capability- Business Capabilities are used to model the capabilities of a business or enterprise. Capabilities represent what the business does (or needs to do) in order to fulfil its objectives and responsibilities.
Examples - Order Approval, Picking, Packing, Delivery, Client Management, Client Invoicing, Trades Matching and Confirmation, Perform Industry Research.
https://www.enterprise-architecture.org/business-architecture-tutorials/55-business-architecture-overview
• Проекты, которые не имеют четких целей, постоянно борются, чтобы понять, каковы их настоящие требования, и вряд ли их обнаружат.
• Проекты без целей уязвимы для давления на добавление требований, даже если у них нет времени или денег для большей работы.
Whether requirements are specified using the “MoSCoW” style (must, should, could, won’t), or as a collection of “user stories,”Они рассказывают, что система должна делать, а не какой она должна быть
Functional - These requirements are satisfied by including an appropriate set of responsibilities within the design.
Quality attribute - These requirements are satisfied by the
structures and behaviors of the architecture.
Constraints - A constraint is a design decision that’s
already been made
История про библиотеку, где я хотел посмотреть каталог.Нужно было зарегистрироваться и указать емайл и телефон!А потом должна была прийти СМС!
Вроде ошибка в определении Quality Attributes
Но с другой стороны Security в приложении важно. Чего-то не хватает?
“In summary, here are the six parts:
Source of stimulus. This is some entity (a human, a computer system, or any other actuator) that generated the stimulus.
2. Stimulus. The stimulus is a condition that requires a response when it arrives at a system.
3. Environment. The stimulus occurs under certain conditions. The system may be in an overload condition or in normal operation, or some other relevant state. For many systems, “normal” operation can refer to one of a number of modes. For these kinds of systems, the environment should specify in which mode the system is executing.
“4. Artifact. Some artifact is stimulated. This may be a collection of systems, the whole system, or some piece or pieces of it.
5. Response. The response is the activity undertaken as the result of the arrival of the stimulus.
6. Response measure. When the response occurs, it should be measurable in some fashion so that the requirement can be tested.
“We call these techniques architectural tactics. A tactic is a design decision that influences the achievement of a quality attribute response—tactics directly affect the system’s response to some stimulus. Tactics impart portability to one design, high performance to another, and integrability to a third
speed up delivery with faster dns-lookup, preconnect, Prefetch and preload
Command Query Responsibility SegregationПодобный паттерн добавляет серьезный оверхед на нашу архитектуру и применение данного паттерна должно быть продиктовано нашим сценарием
Отказоустойчивость
Отказоустойчивость!
Неисправность ошибка падение
Pragmatic Programmers - Release It - Design and Deploy Production-Ready Software.pdf – p.132Avoid Slow Responses and Fail Fast
If your system cannot meet its SLA, inform callers quickly. Don’t make them wait for an error message, and don’t make them wait until they time out. That just makes your problem into their prob- lem.
Reserve resources, verify Integration Points early
In the theme of “don’t do useless work,” make sure you will be able to complete the transaction before you start. If critical resources aren’t available—for example, a popped Circuit Breaker on a required call out—then don’t waste work by getting to that point. The odds of it changing between the beginning and the mid- dle of the transaction are slim.
Use for input validation
Do basic user input validation even before you reserve resources. Don’t bother checking out a database connection, fetching domain objects, populating them, and calling validate( ) just to find out that a required parameter wasn’t entered.
Pragmatic Programmers - Release It - Design and Deploy Production-Ready Software.pdf – p.132Avoid Slow Responses and Fail Fast
If your system cannot meet its SLA, inform callers quickly. Don’t make them wait for an error message, and don’t make them wait until they time out. That just makes your problem into their prob- lem.
Reserve resources, verify Integration Points early
In the theme of “don’t do useless work,” make sure you will be able to complete the transaction before you start. If critical resources aren’t available—for example, a popped Circuit Breaker on a required call out—then don’t waste work by getting to that point. The odds of it changing between the beginning and the mid- dle of the transaction are slim.
Use for input validation
Do basic user input validation even before you reserve resources. Don’t bother checking out a database connection, fetching domain objects, populating them, and calling validate( ) just to find out that a required parameter wasn’t entered.
Автоматический выключатель
На примере приложения, слои это хорошо! Пример на уровне приложения: приложение падало, когда отваливалась база данных
You need to know if an error is transient or intermittent.
Solution:
Define your leaky bucket counter
Initial value at the system start-up
Incrementing wnen specified issue occurs
Decrementing over specified peroid but never less than initial value
If exceeding a predetermined upper threshold, handle the error as permanent
C4 model
System Diagram
Container Diagram
Component Diagram
Technical ARCHITECT’S INFLUENCE
Positive experience with technologies and patterns
Bad experiences are avoided in new designs
Influence by trends
Influence by education and training
Выбор технологий всегда идет последним пунктом при принятии проектного решения:
“The seven categories of architectural design decisions are these:
Allocation of responsibilities
2. Coordination model
3. Data model
4. Management of resources
5. Mapping among architectural elements
6. Binding time decisions
7. Choice of technology
И если в процессе моего доклада вы все-таки начали задумываться о правильной парадигме построения архитектуры в приложениях, то вот вам напоследок еще одна история
В джире у разработчиков не было ни слова написано ни про какие квалити атрибутыОни знать не знали ни про каких стейкхолдеров и реквариментыОни фича за фичей просто топили свое приложениеА теперь поднимите руки, у кого на проекте кто-нибудь занимался чем-то подобным при построении архитектуры? Может вы совершаете ту же ошибку, а может она была совершена ранееА может ваше приложение уже утонуло, а вы еще не знаете об этом?