SlideShare una empresa de Scribd logo
1 de 65
Descargar para leer sin conexión
The working architecture
of NodeJs applications
Viktor Turskyi
CEO at WebbyLab
NodeUkraine 2019
Viktor Turskyi
● CEO and architect at WebbyLab
● 15 years in software development
● Delivered more than 60 projects of
different scale
I want to talk about
● The approach which we polish for 8 years already
● How to build large and small web applications with it
● How we use the same architecture for NodeJs, PHP, Perl web application
● Why we choose Monolith over Microservices first.
● Show real code, not only diagrams.
● What framework to choose.
● How all of it saves us money.
Why we choose monolith by default?
The most popular architecture is...
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: 

Distributed big 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)
● 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)
● Versions compatibility issues (harder to track all dependencies in consistent
state, reduces iterations speed)
● You need more experienced team (hiring issues)
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
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
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
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-
misunderstood-and-unappreciated/
Is Model (MVC) and Domain Model the same?
Model (from MVC)/Domain Logic
● Domain model
● Transaction script
● Table module
● Service layer
Controllers
Services
Domain model
Data access

layer
Dispatcher
Layers
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)
● Web framework independent layer of domain logic
● Learn once, write everywhere
● Well structured
● Works with large and small projects
● Hard to find existing framework which does the the same work.
Why own architecture?
Where do we use this architecture?
● Perl projects (Mojolicious web framework)
● PHP projects (Slim web framework)
● NodeJs (Express web framework)
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 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.
Perl example of a Service class
Rule 2: 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 3: 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/
Rule 4: 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
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
Full example: User registration
User registration: controller/dispatcher
Controllers
Service
User model
Action model
Developers don't have to be full-stack but teams should be.
https://martinfowler.com/bliki/PresentationDomainDataLayering.html
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
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
Telegram: @JABASCRIPT
Viktor Turskyi
viktor@webbylab.com
@koorchik @koorchik
https://webbylab.com

Más contenido relacionado

La actualidad más candente

AngularJS UTOSC
AngularJS UTOSCAngularJS UTOSC
AngularJS UTOSC
roboncode
 
Create Your First "Native" Mobile App with JavaScript + PhoneGap
Create Your First "Native" Mobile App with JavaScript + PhoneGapCreate Your First "Native" Mobile App with JavaScript + PhoneGap
Create Your First "Native" Mobile App with JavaScript + PhoneGap
Steve Phillips
 

La actualidad más candente (20)

Watir The Beginning
Watir The BeginningWatir The Beginning
Watir The Beginning
 
Watir - The Beginning
Watir - The BeginningWatir - The Beginning
Watir - The Beginning
 
JavaScript Power Tools 2015
JavaScript Power Tools 2015JavaScript Power Tools 2015
JavaScript Power Tools 2015
 
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
 
Refactoring to a SPA
Refactoring to a SPARefactoring to a SPA
Refactoring to a SPA
 
Test your user interface using BDD (Swedish)
Test your user interface using BDD (Swedish)Test your user interface using BDD (Swedish)
Test your user interface using BDD (Swedish)
 
MEAN Stack
MEAN Stack MEAN Stack
MEAN Stack
 
AngularJS UTOSC
AngularJS UTOSCAngularJS UTOSC
AngularJS UTOSC
 
Blazor - An Introduction
Blazor - An IntroductionBlazor - An Introduction
Blazor - An Introduction
 
Productive Android developers (Meetup slides)
Productive Android developers (Meetup slides)Productive Android developers (Meetup slides)
Productive Android developers (Meetup slides)
 
C4ainaction-Introduction to the Pyramid Web Framework
C4ainaction-Introduction to the Pyramid Web FrameworkC4ainaction-Introduction to the Pyramid Web Framework
C4ainaction-Introduction to the Pyramid Web Framework
 
Webapps mobiles html5
Webapps mobiles html5Webapps mobiles html5
Webapps mobiles html5
 
Ivan Jovanovic - Micro Frontends - Codemotion Rome_2019
Ivan Jovanovic - Micro Frontends - Codemotion Rome_2019Ivan Jovanovic - Micro Frontends - Codemotion Rome_2019
Ivan Jovanovic - Micro Frontends - Codemotion Rome_2019
 
Nicholas Gustilo "Clean Android: building great mobile apps"
Nicholas Gustilo "Clean Android: building great mobile apps"Nicholas Gustilo "Clean Android: building great mobile apps"
Nicholas Gustilo "Clean Android: building great mobile apps"
 
Focus on the outside, testing in ASP.NET MVC
Focus on the outside, testing in ASP.NET MVCFocus on the outside, testing in ASP.NET MVC
Focus on the outside, testing in ASP.NET MVC
 
Javascript Apps at Build Artifacts
Javascript Apps at Build ArtifactsJavascript Apps at Build Artifacts
Javascript Apps at Build Artifacts
 
Isomorphic JavaScript with Nashorn
Isomorphic JavaScript with NashornIsomorphic JavaScript with Nashorn
Isomorphic JavaScript with Nashorn
 
Full stack web development
Full stack web developmentFull stack web development
Full stack web development
 
Create Your First "Native" Mobile App with JavaScript + PhoneGap
Create Your First "Native" Mobile App with JavaScript + PhoneGapCreate Your First "Native" Mobile App with JavaScript + PhoneGap
Create Your First "Native" Mobile App with JavaScript + PhoneGap
 
Behaviour Driven Development Hands-on
Behaviour Driven Development Hands-onBehaviour Driven Development Hands-on
Behaviour Driven Development Hands-on
 

Similar a "The working architecture of NodeJs applications" Viktor Turskyi

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
 

Similar a "The working architecture of NodeJs applications" Viktor Turskyi (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"
 
The working architecture of NodeJS applications, Виктор Турский
The working architecture of NodeJS applications, Виктор ТурскийThe working architecture of NodeJS applications, Виктор Турский
The working architecture of NodeJS applications, Виктор Турский
 
'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
 
Searching for the framework of my dreams in node.js ecosystem by Mykyta Semen...
Searching for the framework of my dreams in node.js ecosystem by Mykyta Semen...Searching for the framework of my dreams in node.js ecosystem by Mykyta Semen...
Searching for the framework of my dreams in node.js ecosystem by Mykyta Semen...
 
DDD with Behat
DDD with BehatDDD with Behat
DDD with Behat
 
Кирилл Толкачев. Микросервисы: огонь, вода и девопс
Кирилл Толкачев. Микросервисы: огонь, вода и девопсКирилл Толкачев. Микросервисы: огонь, вода и девопс
Кирилл Толкачев. Микросервисы: огонь, вода и девопс
 
Breaking down a monolith
Breaking down a monolithBreaking down a monolith
Breaking down a monolith
 
Microservice pitfalls
Microservice pitfalls Microservice pitfalls
Microservice pitfalls
 
Node.js meetup at Palo Alto Networks Tel Aviv
Node.js meetup at Palo Alto Networks Tel AvivNode.js meetup at Palo Alto Networks Tel Aviv
Node.js meetup at Palo Alto Networks Tel Aviv
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
 
Micro Front-End & Microservices - Plansoft
Micro Front-End & Microservices - PlansoftMicro Front-End & Microservices - Plansoft
Micro Front-End & Microservices - Plansoft
 
Microservice Workshop Hands On
Microservice Workshop Hands On Microservice Workshop Hands On
Microservice Workshop Hands On
 
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
 
Building Microservices with .NET (speaker Anton Vasilenko, Binary Studio)
Building Microservices with .NET (speaker Anton Vasilenko, Binary Studio)Building Microservices with .NET (speaker Anton Vasilenko, Binary Studio)
Building Microservices with .NET (speaker Anton Vasilenko, Binary Studio)
 
Node.js Course 2 of 2 - Advanced techniques
Node.js Course 2 of 2 - Advanced techniquesNode.js Course 2 of 2 - Advanced techniques
Node.js Course 2 of 2 - Advanced techniques
 
Seminar.pptx
Seminar.pptxSeminar.pptx
Seminar.pptx
 
IDEALIZE 2023 - NodeJS & Firebase Session
IDEALIZE 2023 - NodeJS & Firebase SessionIDEALIZE 2023 - NodeJS & Firebase Session
IDEALIZE 2023 - NodeJS & Firebase Session
 
Micro service pitfalls voxxed days istanbul 2015
Micro service pitfalls voxxed days istanbul 2015Micro service pitfalls voxxed days istanbul 2015
Micro service pitfalls voxxed days istanbul 2015
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Android Services Skill Sprint
Android Services Skill SprintAndroid Services Skill Sprint
Android Services Skill Sprint
 

Más de Julia Cherniak

Más de Julia Cherniak (11)

"Definition of Done: Deadline driven development" Vitaliy Ratushnyi
"Definition of Done: Deadline driven development" Vitaliy Ratushnyi"Definition of Done: Deadline driven development" Vitaliy Ratushnyi
"Definition of Done: Deadline driven development" Vitaliy Ratushnyi
 
"Muses Code JS or How Communities Change People" Tanya Butenko
"Muses Code JS or How Communities Change People" Tanya Butenko"Muses Code JS or How Communities Change People" Tanya Butenko
"Muses Code JS or How Communities Change People" Tanya Butenko
 
"Принимают за hard skills, увольняют из-за soft skills" Павел Галушко
"Принимают за hard skills, увольняют из-за soft skills" Павел Галушко"Принимают за hard skills, увольняют из-за soft skills" Павел Галушко
"Принимают за hard skills, увольняют из-за soft skills" Павел Галушко
 
"It’s about time to embrace Streams" Luciano Mammino
"It’s about time to embrace Streams" Luciano Mammino"It’s about time to embrace Streams" Luciano Mammino
"It’s about time to embrace Streams" Luciano Mammino
 
"Node.js and Serverless" Viacheslav Panevskyi
"Node.js and Serverless" Viacheslav Panevskyi"Node.js and Serverless" Viacheslav Panevskyi
"Node.js and Serverless" Viacheslav Panevskyi
 
"Lift me up. Mentorship 101" Tanya Butenko
"Lift me up. Mentorship 101" Tanya Butenko"Lift me up. Mentorship 101" Tanya Butenko
"Lift me up. Mentorship 101" Tanya Butenko
 
"Using Blockchain in Node.js project: JavaScript Ninja’s experience" Maksym D...
"Using Blockchain in Node.js project: JavaScript Ninja’s experience" Maksym D..."Using Blockchain in Node.js project: JavaScript Ninja’s experience" Maksym D...
"Using Blockchain in Node.js project: JavaScript Ninja’s experience" Maksym D...
 
"Black Clouds and Silver Linings in Node.js Security" Liran Tal
"Black Clouds and Silver Linings in Node.js Security" Liran Tal"Black Clouds and Silver Linings in Node.js Security" Liran Tal
"Black Clouds and Silver Linings in Node.js Security" Liran Tal
 
"The search for App-iness : Progressive Web Apps" Jamie Maria Schouren
"The search for App-iness : Progressive Web Apps" Jamie Maria Schouren"The search for App-iness : Progressive Web Apps" Jamie Maria Schouren
"The search for App-iness : Progressive Web Apps" Jamie Maria Schouren
 
"The Future of Machine Learning & JavaScript"Asim Hussain
"The Future of Machine Learning & JavaScript"Asim Hussain"The Future of Machine Learning & JavaScript"Asim Hussain
"The Future of Machine Learning & JavaScript"Asim Hussain
 
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun..."ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
"ClojureScript journey: from little script, to CLI program, to AWS Lambda fun...
 

Último

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Último (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 

"The working architecture of NodeJs applications" Viktor Turskyi

  • 1. The working architecture of NodeJs applications Viktor Turskyi CEO at WebbyLab NodeUkraine 2019
  • 2. Viktor Turskyi ● CEO and architect at WebbyLab ● 15 years in software development ● Delivered more than 60 projects of different scale
  • 3. I want to talk about ● The approach which we polish for 8 years already ● How to build large and small web applications with it ● How we use the same architecture for NodeJs, PHP, Perl web application ● Why we choose Monolith over Microservices first. ● Show real code, not only diagrams. ● What framework to choose. ● How all of it saves us money.
  • 4. Why we choose monolith by default?
  • 5. The most popular architecture is...
  • 6. Big Ball of Mud http://www.laputan.org/mud/mud.html#BigBallOfMud
  • 7. If Monolith is a big ball of mud.
 Will it be better with Microservices?
  • 9.
  • 10. "If you cannot build a monolith what makes you think that you can build Distributed Microservices" Simon Brown
  • 11.
  • 13. Microservices drawbacks ● High operational complexity (increases costs) ● 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) ● Versions compatibility issues (harder to track all dependencies in consistent state, reduces iterations speed) ● You need more experienced team (hiring issues)
  • 14. 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
  • 15. 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
  • 18.
  • 20. NodeJs frameworks ● Express ● Koa ● Sails ● Nest ● Feathers ● Derby ● Kraken ● Hapi ● etc
  • 22. Your application architecture should not depend on a web framework
  • 23. Web frameworks we use NodeJs: Express PHP: Slim3 Perl : Mojolicious
  • 25. Where to place this code? Model or Controller?
  • 26. 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- misunderstood-and-unappreciated/
  • 27. Is Model (MVC) and Domain Model the same?
  • 28. Model (from MVC)/Domain Logic ● Domain model ● Transaction script ● Table module ● Service layer
  • 29.
  • 31. 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
  • 32. 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)
  • 33. 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)
  • 34. ● Web framework independent layer of domain logic ● Learn once, write everywhere ● Well structured ● Works with large and small projects ● Hard to find existing framework which does the the same work. Why own architecture?
  • 35. Where do we use this architecture? ● Perl projects (Mojolicious web framework) ● PHP projects (Slim web framework) ● NodeJs (Express web framework)
  • 36. Core patterns in the architecture Application level (Martin Fowler): ● MVC ● Service layer ● Domain model Class level (GoF): ● Template method ● Command
  • 37. How do we cook the service layer?
  • 38. Rule 1: Separate service class for each endpoint
  • 39. Real code (with meta programming)
  • 40. NodeJs example of a Service class
  • 41.
  • 42. Base class (the simplest version)
  • 43. “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.
  • 44. Perl example of a Service class
  • 45.
  • 46.
  • 47. Rule 2: 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
  • 48. Rule 3: 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
  • 49. 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/
  • 50. Rule 4: 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
  • 51. 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
  • 52. Full example: User registration
  • 53.
  • 54.
  • 58.
  • 61. Developers don't have to be full-stack but teams should be. https://martinfowler.com/bliki/PresentationDomainDataLayering.html
  • 62. 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
  • 63. 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