SlideShare uma empresa Scribd logo
1 de 74
Baixar para ler offline
The working architecture of
NodeJs applications
Viktor Turskyi
Viktor Turskyi
● CEO and principal architect at
WebbyLab
● Open source developer
● More than 15 years of experience
● Delivered more than 60 projects of
different scale
● Did projects for 5 companies from
Fortune 500 list
Why do I talk about architecture?
● The importance of good architecture is often underestimated.
● There are a lot of “Hello, world” tutorials for NodeJs but no one explain how to
build a large scale project.
● A lot of frontend developers want to be full stack but do know how to structure
backend code.
● I want to share our experience with the community
Why do I call it the working architecture?
● It is in production for 8 years.
● It is battle tested with more than 60 projects of different scale.
● It proved itself as working approach in NodeJs, PHP, Perl web application
During this talk I will:
● I will answer what to choose Monolith or Microservices?
● Will answer which web-framework to choose.
● Explain basic ideas behind the architecture
● Show real code, not only diagrams.
Monolith or Microservices by default?
What is the most popular architecture
today?
Big Ball of Mud
http://www.laputan.org/mud/mud.html#BigBallOfMud
If Monolith is a big ball of mud.
Will it be better with Microservices?
Microservices:
Big and distributed ball of mud
"If you cannot build a monolith what makes you think that you
can build Distributed Microservices"
Simon Brown
Microservice architecture visualized
https://twitter.com/ThePracticalDev/status/845285541528719360
Microservices drawbacks
● High operational complexity (increases costs)
● Versions compatibility issues (harder to track all dependencies in consistent
state, reduces iterations speed)
● Extremely hard to support transactions (risks of inconsistencies)
● Distribution issues (harder to program)
● Traceability issues (harder to debug)
● Technology diversity (mixing languages increases support costs,
standardization issues, hiring issues etc)
● You need more experienced team (hiring issues)
Key microservices issue
What is the best architectural decision?
Robert Martin:
“The job of architect is not to make decision, the job of
the architect is to defer decisions as long as possible”
“Good architecture maximizes number of decisions not
made”
https://www.youtube.com/watch?v=o_TH-Y78tt4
Martin Fowler:
● But when your components are services with remote communications, then
refactoring is much harder than with in-process libraries.
● Another issue is If the components do not compose cleanly, then all you are
doing is shifting complexity from inside a component to the connections
between components. Not just does this just move complexity around, it
moves it to a place that's less explicit and harder to control.
https://martinfowler.com/bliki/MonolithFirst.html
So, we start with monolith in 90% of
cases
What is Monolith?
Usually it looks like
Which web-framework to choose?
NodeJs frameworks
● Express
● Koa
● Sails
● Nest
● Feathers
● Derby
● Kraken
● Hapi
● etc
It doesn’t matter!
Your application architecture should not depend on a
web framework
Web frameworks we use
NodeJs: Express
PHP: Slim3
Perl : Mojolicious
“We use MVC why do we need another
architecture?”
MVC (from wikipedia)
Where to place this code? Model or Controller?
Fat Stupid Ugly Controllers
“The M in MVC: Why Models are Misunderstood and Unappreciated” Pádraic
Brady
http://blog.astrumfutura.com/2008/12/the-m-in-mvc-why-models-are-misunderstoo
d-and-unappreciated/
Is Model (MVC) and Domain Model the same?
Model (from MVC)/Domain Logic
● Domain model
● Transaction script
● Table module
● Service layer
Domain model
An object model of the domain that incorporates both
behavior and data. (M. Fowler)
Works well for medium and large applications
Transaction script
Organizes business logic by procedures where each
procedure handles a single request from the presentation (M.
Fowler).
Works well for small projects
Controllers
Services
Domain model
Data access
layer
Dispatcher
The way of thinking about Controllers
● Extremely thin layer
● Protects underneath layers from everything related to HTTP
● If you change JSON to XML (or even CLI), only controllers should be rewritten
The way of thinking about Domain Model
● Belongs to Model layer of MVC
● The core part of your application
● You have almost all of your business logic here (not only database access)!!!
● Knows nothing about service layer and upper layers
● Responsible for data storing and data integrity
● Fine grained API (not suited for remote invocation)
The way of thinking about Services
● Belongs to Model layer of MVC
● Contains application logic
● Does not trust any incoming params
● You should keep thin if possible
● Knows nothing about controllers/transport/UI.
● Use cases based API
● Knows about context (what user asks for data)
● Knows when and how to notify user (emails etc)
● Does coordination and security
● Coarse grained API (well suited for remote invocation)
Core patterns in the architecture
Application level (Martin Fowler):
● MVC
● Service layer
● Domain model
Class level (GoF):
● Template method
● Command
How do we cook the service layer?
Rule 1: Separate service class (implemented a
command) for each endpoint
Real code (with meta programming)
NodeJs example of a Service class
Base class (the simplest version)
“run” method
Template method in base class
Guarantees that all procedures are kept:
● Data was validated
● “execute” will be called only after validation
● “execute” will receive only clean data
● Checks permissions before calling “execute”
● Throws exception in case of validation errors.
Can do extra work like caching validator objects, etc.
Rule 2: Never return objects directly
Whitelist every object
property:
1. You know what you return
(that no internal/secret
data there)
2. Your API is stable
Rule 3: There is no excuse for not using Promises or
await/async today
● Error handling - one of the most powerful promise features. You can structure
your error processing in a much better way with promises.
● You will never see “uncaughtException”
● You will have manageable code
Rule 4: Unified approach to validation
● DO NOT TRUST ANY USER INPUT! NEVER!!!
● Declarative validation
● Exclude all fields that do not have validation rules described
● Returns understandable error codes (neither error messages nor numeric
codes)
● It should be clear for the service user what is wrong with his data
We use LIVR for the validation
It supports:
● JavaScript
● Perl
● Perl 6
● PHP
● Go
● Erlang
● Python
● Ruby
● Java
● Lua
Details are here - http://livr-spec.org/
It should be clear where any code should be! Otherwise you do not architecture.
One of the risks, than you can end up with an “Anemic domain model”
(https://www.martinfowler.com/bliki/AnemicDomainModel.html)
If you have a large project, this can be a reason of project failure as you will
implicitly switch to “transaction script” approach which is not well suited for large
applications.
Rule 5: Be aware of “Anemic domain model”
antipattern
Perl example of a Service class
GraphQL support
Full example: User registration
User registration: controller/dispatcher
Controllers
Service
User model
Action model
Main benefits
● NodeJs, PHP, Perl - the same architecture.
● Works with small and large projects
● Extremely flexible.
● Ease to start.
● Much cheaper for company to support the same approach on all projects.
● Web framework agnostic and based on micro frameworks which is easy to learn for
new person.
● Cheaper technology switch (for example from PHP to NodeJs).
● Cheaper communication.
● Knowledge sharing (larger core).
● Higher resources utilization.
● Monolith first approach and modular architecture allows us to switch to Microservices
later
FAQ
Q: Do we use 12-factor approach?
A: Yes, it is a part of boilerplate.
Q: Is it ok to call a service from service
A: We do not do this. If you need the same logic reuse, possibly it should go to Domain
Model.
Q: Is it ok to place methods in sequelize models?
A: Yes, it the idea of any ORM! Otherwise it will be Anemic Domain Model
Useful links
MonolithFirst by Martin Fowler
Microservice Trade-Offs by Martin Fowler
PresentationDomainDataLayering by Martin Fowler
The Principles of Clean Architecture by Uncle Bob Martin
The Clean Architecture by Robert Martin
Microservice Architecture at Medium
https://12factor.net/
NodeJs Starter Kit (this year)
● Based on ideas of Clean Architecture
● Works with small and large projects
● Follows 12 factor app approach
● Modern JS (including ES6 for Sequalize)
● Supports both REST API and GraphQL
● Follows security best practices.
● Docker support
● Covered with tests
● Battle tested
● Built on top of express.js
● Users management
Telegram: @JABASCRIPT
Viktor Turskyi
@koorchik

Mais conteúdo relacionado

Mais procurados

Good code, Bad Code
Good code, Bad CodeGood code, Bad Code
Good code, Bad Code
josedasilva
 

Mais procurados (12)

React web development
React web developmentReact web development
React web development
 
How to write bad code using C#
How to write bad code using C#How to write bad code using C#
How to write bad code using C#
 
Geecon10: Object Oriented for nonbelievers
Geecon10: Object Oriented for nonbelieversGeecon10: Object Oriented for nonbelievers
Geecon10: Object Oriented for nonbelievers
 
How we tested our code "Google way"
How we tested our code "Google way"How we tested our code "Google way"
How we tested our code "Google way"
 
TDD done right - tests immutable to refactor
TDD done right - tests immutable to refactorTDD done right - tests immutable to refactor
TDD done right - tests immutable to refactor
 
Hexagonal Symfony - SymfonyCon Amsterdam 2019
Hexagonal Symfony - SymfonyCon Amsterdam 2019Hexagonal Symfony - SymfonyCon Amsterdam 2019
Hexagonal Symfony - SymfonyCon Amsterdam 2019
 
Create first android app with MVVM Architecture
Create first android app with MVVM ArchitectureCreate first android app with MVVM Architecture
Create first android app with MVVM Architecture
 
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...Brutal refactoring, lying code, the Churn, and other emotional stories from L...
Brutal refactoring, lying code, the Churn, and other emotional stories from L...
 
Good code, Bad Code
Good code, Bad CodeGood code, Bad Code
Good code, Bad Code
 
Clean code quotes - Citações e provocações
Clean code quotes - Citações e provocaçõesClean code quotes - Citações e provocações
Clean code quotes - Citações e provocações
 
The Professional Programmer
The Professional ProgrammerThe Professional Programmer
The Professional Programmer
 
Magento 2 - Replacing God with Dependency Injection
Magento 2  - Replacing God with Dependency InjectionMagento 2  - Replacing God with Dependency Injection
Magento 2 - Replacing God with Dependency Injection
 

Semelhante a The working architecture of NodeJS applications, Виктор Турский

Network Automation Journey, A systems engineer NetOps perspective
Network Automation Journey, A systems engineer NetOps perspectiveNetwork Automation Journey, A systems engineer NetOps perspective
Network Automation Journey, A systems engineer NetOps perspective
Walid Shaari
 

Semelhante a The working architecture of NodeJS applications, Виктор Турский (20)

Viktor Turskyi "Effective NodeJS Application Development"
Viktor Turskyi "Effective NodeJS Application Development"Viktor Turskyi "Effective NodeJS Application Development"
Viktor Turskyi "Effective NodeJS Application Development"
 
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
'Effective node.js development' by Viktor Turskyi at OdessaJS'2020
 
"The working architecture of NodeJs applications" Viktor Turskyi
"The working architecture of NodeJs applications" Viktor Turskyi"The working architecture of NodeJs applications" Viktor Turskyi
"The working architecture of NodeJs applications" Viktor Turskyi
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Breaking down a monolith
Breaking down a monolithBreaking down a monolith
Breaking down a monolith
 
Not my problem - Delegating responsibility to infrastructure
Not my problem - Delegating responsibility to infrastructureNot my problem - Delegating responsibility to infrastructure
Not my problem - Delegating responsibility to infrastructure
 
DDD with Behat
DDD with BehatDDD with Behat
DDD with Behat
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
 
Bringing it all together
Bringing it all togetherBringing it all together
Bringing it all together
 
From class to architecture
From class to architectureFrom class to architecture
From class to architecture
 
Indy meetup#7 effective unit-testing-mule
Indy meetup#7 effective unit-testing-muleIndy meetup#7 effective unit-testing-mule
Indy meetup#7 effective unit-testing-mule
 
Ledingkart Meetup #1: Monolithic to microservices in action
Ledingkart Meetup #1: Monolithic to microservices in actionLedingkart Meetup #1: Monolithic to microservices in action
Ledingkart Meetup #1: Monolithic to microservices in action
 
Laptop Devops: Putting Modern Infrastructure Automation to Work For Local Dev...
Laptop Devops: Putting Modern Infrastructure Automation to Work For Local Dev...Laptop Devops: Putting Modern Infrastructure Automation to Work For Local Dev...
Laptop Devops: Putting Modern Infrastructure Automation to Work For Local Dev...
 
DevOps State of the Union 2015
DevOps State of the Union 2015DevOps State of the Union 2015
DevOps State of the Union 2015
 
Services, dependencies, and you
Services, dependencies, and youServices, dependencies, and you
Services, dependencies, and you
 
Intro to ember.js
Intro to ember.jsIntro to ember.js
Intro to ember.js
 
Monolithic to Microservices Architecture - STM 6
Monolithic to Microservices Architecture - STM 6Monolithic to Microservices Architecture - STM 6
Monolithic to Microservices Architecture - STM 6
 
Meetup 2020 - Back to the Basics part 101 : IaC
Meetup 2020 - Back to the Basics part 101 : IaCMeetup 2020 - Back to the Basics part 101 : IaC
Meetup 2020 - Back to the Basics part 101 : IaC
 
Network Automation Journey, A systems engineer NetOps perspective
Network Automation Journey, A systems engineer NetOps perspectiveNetwork Automation Journey, A systems engineer NetOps perspective
Network Automation Journey, A systems engineer NetOps perspective
 
From prototype to production - The journey of re-designing SmartUp.io
From prototype to production - The journey of re-designing SmartUp.ioFrom prototype to production - The journey of re-designing SmartUp.io
From prototype to production - The journey of re-designing SmartUp.io
 

Mais de Sigma Software

Mais de Sigma Software (20)

Fast is Best. Using .NET MinimalAPIs
Fast is Best. Using .NET MinimalAPIsFast is Best. Using .NET MinimalAPIs
Fast is Best. Using .NET MinimalAPIs
 
"Are you developing or declining? Don't become an IT-dinosaur"
"Are you developing or declining? Don't become an IT-dinosaur""Are you developing or declining? Don't become an IT-dinosaur"
"Are you developing or declining? Don't become an IT-dinosaur"
 
Michael Smolin, "Decrypting customer's cultural code"
Michael Smolin, "Decrypting customer's cultural code"Michael Smolin, "Decrypting customer's cultural code"
Michael Smolin, "Decrypting customer's cultural code"
 
Max Kunytsia, “Why is continuous product discovery better than continuous del...
Max Kunytsia, “Why is continuous product discovery better than continuous del...Max Kunytsia, “Why is continuous product discovery better than continuous del...
Max Kunytsia, “Why is continuous product discovery better than continuous del...
 
Marcelino Moreno, "Product Management Mindset"
Marcelino Moreno, "Product Management Mindset"Marcelino Moreno, "Product Management Mindset"
Marcelino Moreno, "Product Management Mindset"
 
Andrii Pastushok, "Product Discovery in Outsourcing - What, When, and How"
Andrii Pastushok, "Product Discovery in Outsourcing - What, When, and How"Andrii Pastushok, "Product Discovery in Outsourcing - What, When, and How"
Andrii Pastushok, "Product Discovery in Outsourcing - What, When, and How"
 
Elena Turkenych “BA vs PM: Who' the right person, for the right job, with the...
Elena Turkenych “BA vs PM: Who' the right person, for the right job, with the...Elena Turkenych “BA vs PM: Who' the right person, for the right job, with the...
Elena Turkenych “BA vs PM: Who' the right person, for the right job, with the...
 
Eleonora Budanova “BA+PM+DEV team: how to build the synergy”
Eleonora Budanova “BA+PM+DEV team: how to build the synergy”Eleonora Budanova “BA+PM+DEV team: how to build the synergy”
Eleonora Budanova “BA+PM+DEV team: how to build the synergy”
 
Stoyan Atanasov “How crucial is the BA role in an IT Project"
Stoyan Atanasov “How crucial is the BA role in an IT Project"Stoyan Atanasov “How crucial is the BA role in an IT Project"
Stoyan Atanasov “How crucial is the BA role in an IT Project"
 
Olexandra Kovalyova, "Equivalence Partitioning, Boundary Values ​​Analysis, C...
Olexandra Kovalyova, "Equivalence Partitioning, Boundary Values ​​Analysis, C...Olexandra Kovalyova, "Equivalence Partitioning, Boundary Values ​​Analysis, C...
Olexandra Kovalyova, "Equivalence Partitioning, Boundary Values ​​Analysis, C...
 
Yana Lysa — "Decision Tables, State-Transition testing, Pairwase Testing"
Yana Lysa — "Decision Tables, State-Transition testing, Pairwase Testing"Yana Lysa — "Decision Tables, State-Transition testing, Pairwase Testing"
Yana Lysa — "Decision Tables, State-Transition testing, Pairwase Testing"
 
VOLVO x HACK SPRINT
VOLVO x HACK SPRINTVOLVO x HACK SPRINT
VOLVO x HACK SPRINT
 
Business digitalization trends and challenges
Business digitalization trends and challengesBusiness digitalization trends and challenges
Business digitalization trends and challenges
 
Дмитро Терещенко, "How to secure your application with Secure SDLC"
Дмитро Терещенко, "How to secure your application with Secure SDLC"Дмитро Терещенко, "How to secure your application with Secure SDLC"
Дмитро Терещенко, "How to secure your application with Secure SDLC"
 
Яна Лиса, “Ефективні методи написання хороших мануальних тестових сценаріїв”
Яна Лиса, “Ефективні методи написання хороших мануальних тестових сценаріїв”Яна Лиса, “Ефективні методи написання хороших мануальних тестових сценаріїв”
Яна Лиса, “Ефективні методи написання хороших мануальних тестових сценаріїв”
 
Тетяна Осетрова, “Модель зрілості розподіленної проектної команди”
Тетяна Осетрова, “Модель зрілості розподіленної проектної команди”Тетяна Осетрова, “Модель зрілості розподіленної проектної команди”
Тетяна Осетрова, “Модель зрілості розподіленної проектної команди”
 
Training solutions and content creation
Training solutions and content creationTraining solutions and content creation
Training solutions and content creation
 
False news - false truth: tips & tricks how to avoid them
False news - false truth: tips & tricks how to avoid themFalse news - false truth: tips & tricks how to avoid them
False news - false truth: tips & tricks how to avoid them
 
Анна Бойко, "Хороший контракт vs очікування клієнтів. Що вбереже вас, якщо вд...
Анна Бойко, "Хороший контракт vs очікування клієнтів. Що вбереже вас, якщо вд...Анна Бойко, "Хороший контракт vs очікування клієнтів. Що вбереже вас, якщо вд...
Анна Бойко, "Хороший контракт vs очікування клієнтів. Що вбереже вас, якщо вд...
 
Дмитрий Лапшин, "The importance of TEX and Internal Quality. How explain and ...
Дмитрий Лапшин, "The importance of TEX and Internal Quality. How explain and ...Дмитрий Лапшин, "The importance of TEX and Internal Quality. How explain and ...
Дмитрий Лапшин, "The importance of TEX and Internal Quality. How explain and ...
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

The working architecture of NodeJS applications, Виктор Турский

  • 1. The working architecture of NodeJs applications Viktor Turskyi
  • 2. Viktor Turskyi ● CEO and principal architect at WebbyLab ● Open source developer ● More than 15 years of experience ● Delivered more than 60 projects of different scale ● Did projects for 5 companies from Fortune 500 list
  • 3. Why do I talk about architecture? ● The importance of good architecture is often underestimated. ● There are a lot of “Hello, world” tutorials for NodeJs but no one explain how to build a large scale project. ● A lot of frontend developers want to be full stack but do know how to structure backend code. ● I want to share our experience with the community
  • 4. Why do I call it the working architecture? ● It is in production for 8 years. ● It is battle tested with more than 60 projects of different scale. ● It proved itself as working approach in NodeJs, PHP, Perl web application
  • 5. During this talk I will: ● I will answer what to choose Monolith or Microservices? ● Will answer which web-framework to choose. ● Explain basic ideas behind the architecture ● Show real code, not only diagrams.
  • 7. What is the most popular architecture today?
  • 8. Big Ball of Mud http://www.laputan.org/mud/mud.html#BigBallOfMud
  • 9. If Monolith is a big ball of mud. Will it be better with Microservices?
  • 11.
  • 12. "If you cannot build a monolith what makes you think that you can build Distributed Microservices" Simon Brown
  • 13.
  • 15. Microservices drawbacks ● High operational complexity (increases costs) ● Versions compatibility issues (harder to track all dependencies in consistent state, reduces iterations speed) ● Extremely hard to support transactions (risks of inconsistencies) ● Distribution issues (harder to program) ● Traceability issues (harder to debug) ● Technology diversity (mixing languages increases support costs, standardization issues, hiring issues etc) ● You need more experienced team (hiring issues)
  • 17. What is the best architectural decision?
  • 18. Robert Martin: “The job of architect is not to make decision, the job of the architect is to defer decisions as long as possible” “Good architecture maximizes number of decisions not made” https://www.youtube.com/watch?v=o_TH-Y78tt4
  • 19. Martin Fowler: ● But when your components are services with remote communications, then refactoring is much harder than with in-process libraries. ● Another issue is If the components do not compose cleanly, then all you are doing is shifting complexity from inside a component to the connections between components. Not just does this just move complexity around, it moves it to a place that's less explicit and harder to control. https://martinfowler.com/bliki/MonolithFirst.html
  • 20. So, we start with monolith in 90% of cases
  • 23.
  • 25. NodeJs frameworks ● Express ● Koa ● Sails ● Nest ● Feathers ● Derby ● Kraken ● Hapi ● etc
  • 27. Your application architecture should not depend on a web framework
  • 28. Web frameworks we use NodeJs: Express PHP: Slim3 Perl : Mojolicious
  • 29. “We use MVC why do we need another architecture?”
  • 31. Where to place this code? Model or Controller?
  • 32. Fat Stupid Ugly Controllers “The M in MVC: Why Models are Misunderstood and Unappreciated” Pádraic Brady http://blog.astrumfutura.com/2008/12/the-m-in-mvc-why-models-are-misunderstoo d-and-unappreciated/
  • 33. Is Model (MVC) and Domain Model the same?
  • 34. Model (from MVC)/Domain Logic ● Domain model ● Transaction script ● Table module ● Service layer
  • 35. Domain model An object model of the domain that incorporates both behavior and data. (M. Fowler) Works well for medium and large applications
  • 36. Transaction script Organizes business logic by procedures where each procedure handles a single request from the presentation (M. Fowler). Works well for small projects
  • 37.
  • 39.
  • 40. The way of thinking about Controllers ● Extremely thin layer ● Protects underneath layers from everything related to HTTP ● If you change JSON to XML (or even CLI), only controllers should be rewritten
  • 41. The way of thinking about Domain Model ● Belongs to Model layer of MVC ● The core part of your application ● You have almost all of your business logic here (not only database access)!!! ● Knows nothing about service layer and upper layers ● Responsible for data storing and data integrity ● Fine grained API (not suited for remote invocation)
  • 42. The way of thinking about Services ● Belongs to Model layer of MVC ● Contains application logic ● Does not trust any incoming params ● You should keep thin if possible ● Knows nothing about controllers/transport/UI. ● Use cases based API ● Knows about context (what user asks for data) ● Knows when and how to notify user (emails etc) ● Does coordination and security ● Coarse grained API (well suited for remote invocation)
  • 43. Core patterns in the architecture Application level (Martin Fowler): ● MVC ● Service layer ● Domain model Class level (GoF): ● Template method ● Command
  • 44. How do we cook the service layer?
  • 45. Rule 1: Separate service class (implemented a command) for each endpoint
  • 46. Real code (with meta programming)
  • 47. NodeJs example of a Service class
  • 48. Base class (the simplest version)
  • 49.
  • 50. “run” method Template method in base class Guarantees that all procedures are kept: ● Data was validated ● “execute” will be called only after validation ● “execute” will receive only clean data ● Checks permissions before calling “execute” ● Throws exception in case of validation errors. Can do extra work like caching validator objects, etc.
  • 51. Rule 2: Never return objects directly Whitelist every object property: 1. You know what you return (that no internal/secret data there) 2. Your API is stable
  • 52. Rule 3: There is no excuse for not using Promises or await/async today ● Error handling - one of the most powerful promise features. You can structure your error processing in a much better way with promises. ● You will never see “uncaughtException” ● You will have manageable code
  • 53. Rule 4: Unified approach to validation ● DO NOT TRUST ANY USER INPUT! NEVER!!! ● Declarative validation ● Exclude all fields that do not have validation rules described ● Returns understandable error codes (neither error messages nor numeric codes) ● It should be clear for the service user what is wrong with his data
  • 54. We use LIVR for the validation It supports: ● JavaScript ● Perl ● Perl 6 ● PHP ● Go ● Erlang ● Python ● Ruby ● Java ● Lua Details are here - http://livr-spec.org/
  • 55. It should be clear where any code should be! Otherwise you do not architecture. One of the risks, than you can end up with an “Anemic domain model” (https://www.martinfowler.com/bliki/AnemicDomainModel.html) If you have a large project, this can be a reason of project failure as you will implicitly switch to “transaction script” approach which is not well suited for large applications. Rule 5: Be aware of “Anemic domain model” antipattern
  • 56. Perl example of a Service class
  • 57.
  • 58.
  • 60.
  • 61.
  • 62. Full example: User registration
  • 66.
  • 69. Main benefits ● NodeJs, PHP, Perl - the same architecture. ● Works with small and large projects ● Extremely flexible. ● Ease to start. ● Much cheaper for company to support the same approach on all projects. ● Web framework agnostic and based on micro frameworks which is easy to learn for new person. ● Cheaper technology switch (for example from PHP to NodeJs). ● Cheaper communication. ● Knowledge sharing (larger core). ● Higher resources utilization. ● Monolith first approach and modular architecture allows us to switch to Microservices later
  • 70. FAQ Q: Do we use 12-factor approach? A: Yes, it is a part of boilerplate. Q: Is it ok to call a service from service A: We do not do this. If you need the same logic reuse, possibly it should go to Domain Model. Q: Is it ok to place methods in sequelize models? A: Yes, it the idea of any ORM! Otherwise it will be Anemic Domain Model
  • 71. Useful links MonolithFirst by Martin Fowler Microservice Trade-Offs by Martin Fowler PresentationDomainDataLayering by Martin Fowler The Principles of Clean Architecture by Uncle Bob Martin The Clean Architecture by Robert Martin Microservice Architecture at Medium https://12factor.net/
  • 72. NodeJs Starter Kit (this year) ● Based on ideas of Clean Architecture ● Works with small and large projects ● Follows 12 factor app approach ● Modern JS (including ES6 for Sequalize) ● Supports both REST API and GraphQL ● Follows security best practices. ● Docker support ● Covered with tests ● Battle tested ● Built on top of express.js ● Users management