SlideShare a Scribd company logo
1 of 60
Download to read offline
Microservices in
Mariusz Richtscheid
Gliwice, 10.10.2018
patterns and techniques
About me
• Full-Stack Developer in The Software House

• richtscheid@gmail.com

• linkedin.com/in/richtscheid

• github.com/barograf
Mariusz Richtscheid
Agenda
• Why microservices?

• Communication patterns

• Data management patterns

• Reliability and observability patterns

• Testing
Monolith
• Can be difficult to understand and modify

• Development and deployments slow down over time

• Modularity breaks down over time

• Quality of the code declines over time

• It is hard to change technology stack
Why microservices?
• Smaller services are easier to understand and test

• Services can be deployed more frequently

• Development in multiple teams

• Improved fault isolation

• Every service can have different technology stack
A lot of issues to address
How to decompose into services?
How to deploy?
How to handle configs, logging,
tracing, health checks, metrics?
How to communicate between services?
How do external clients
communicate with the services?
What about service discovery?
How to prevent failures?
How to maintain data consistency?
How to handle security? How to test it?
How to troubleshoot problems?
How to display data from multiple
services?
Solution: patterns!
Source: https://microservices.io/patterns/microservices.html
API Gateway
API Gateway overview
Service 1 Service 2
API GatewayClient Service 3
System
Client
✔
❌
API Gateway
• One entry point for the entire system

• Handles security - other services communicate freely

• Knows how to call other services - statically defined or with service
discovery

• Should not contain business logic
API Gateway - message format
export interface ISocketMessage {
serviceName: string;
serviceOperation: string;
payload: object;
}
API Gateway - handling requests
client.on('message', (data: ISocketMessage) => {
this.services[data.serviceName][data.serviceOperation]({
...data.payload
})
.then(result => {
client.emit('message', { payload: result });
})
.catch(error => {
/*
please log me
*/
});
});
Service discovery
Service discovery
Router
Service registry
Service 1
RegisterGet address
Request
Service 2
Request
• Solution to connect and configure applications across distributed
infrastructure

• Service discovery

• Health checking

• Provides useful UI
Consul UI - services
Consul UI - health checks
Running Consul server
Health check endpoint
const app = express();
app.get('/health', (req, res) => {
res.status(200);
res.send('ok');
res.end();
});
Service and health check registration
const consul = require('consul')();
consul.agent.service.register({
name: 'api-gateway',
address: process.env.HOST,
port: Number(process.env.PORT),
check: {
http: `http://${process.env.HOST}:${process.env.PORT}/health`,
interval: '30s',
}
}, err => { if (err) throw err });
Health check subscription
consul
.watch({
method: consul.health.service,
options: { service: 'translations' }
})
.on('change', function (data, res) {
const status = data[0].Checks[1].Status;
console.log(`translations service status: ${status}`);
});
Health check subscription
Communication between services
Remote procedure invocation
API GatewayClient
System
Service 1 Service 2
https://
Apache
Thrift
Message broker
API GatewayClient
Service 1
Message broker
Service 2
Pub/Sub
• Loose
coupling

• Buffering
messages
Data management
Shared database
Service 1
API GatewayClient Service 2
System
Shared

database
Database per service
Service 1
API GatewayClient Service 2
System
Service 1

database
Service 2

database
• Scaling

• Data
consistency

• Queries
Data consistency - Saga
Saga
• A service which coordinates sequence of local transactions across
multiple microservices

• Each local transaction updates the database

• If local transaction fails then the saga executes a rollback for all related
microservices
Rollback in saga
Service 1
Operation 1
Operation 2
Operation 3
Saga
Service 2
Service 3
Service 4
❌
✅
✅
Service 4Rollback✅ Error
Data changed
Data changed
Querying - API Composition
API Composition
API GatewayClient Service 1
System
Query Query Query
Service 2 Service 3 Service 4
Circuit breaker
Circuit breaker
• Mechanism for fast fail of requests towards unhealthy services

• Prevents unnecessary traffic and cascading fails

• Unhealthy services can recover safely
Circuit breaker
Service 2
API GatewayClient Service 1
System
Service 1
Error
Distributed tracing
Distributed tracing
• Logging is not enough in distributed system

• Tracing gives insight into code execution across services

• With tracing we know what, where and when something fails
Distributed tracing overview
Service 2
API GatewayClient
Tracing server
Service 1
System
Tracing ID (e.g. header)
Tracing ID
• Standard for distributed tracing

• Defines interfaces and data model for many programming languages

• Has no real implementation
• OpenTracing compatible implementation for distributed tracing

• Released as open source by Uber Technologies

• Available in Node, Go, Java, Python and C++

• Provides useful UI
Jaeger UI
traces list
Jaeger UI - trace details
Span
Jaeger UI - span details
Running Jaeger server
Initializing tracer
import { initTracer } from 'jaeger-client';
const tracer = initTracer(
{
serviceName: process.env.APP_NAME || 'Unknown app',
sampler: {
type: 'const',
param: 1,
},
reporter: {
logSpans: true,
agentHost: process.env.TRACING_SERVICE_HOST || 'localhost',
agentPort: Number(process.env.TRACING_SERVICE_PORT) || 6832,
},
},
{ logger }
);
Creating new span
const span = tracer.startSpan('name of the span');
span.addTags({ type: 'foo' });
/*
some code
*/
span.finish();
Sending tracing ID
import { FORMAT_HTTP_HEADERS } from 'opentracing';
const headers = {};
tracer.inject(span, FORMAT_HTTP_HEADERS, headers);
const tracingId = JSON.stringify(headers);
/*
send tracing ID to other service (with headers, as string value etc.)
*/
Receiving tracing ID
/*
receive tracing ID from other service
*/
const tracingIdString = '{"uber-trace-id":"d7ee8bcc3f4a1033:d7ee8bcc3f4a1033:0:1"}';
const spanFromOtherService = tracer.extract(
FORMAT_HTTP_HEADERS,
JSON.parse(tracingIdString)
);
const span = tracer.startSpan('name of the span', { childOf: spanFromOtherService });
/*
some code
*/
span.finish();
Testing
Testing
• Specs are not enough

• Write integration tests for parts of your infrastructure

• Run your infrastructure with one command

• Can be achieved with Docker Compose or PM2 ecosystem

• Different definitions for different parts of infrastructure
PM2 - ecosystem.json
{
"apps": [
{
"name": "API Gateway",
"script": "index.ts",
"cwd": "src/services/api-gateway"
},
{
"name": "Notifications service",
"script": "index.ts",
"cwd": "src/services/notifications"
}
]
}
• Requires mono-repository

• For Node scripts only
docker-compose.yml
version: '3'
services:
api-gateway:
image: org/api-gateway:latest
ports:
- "3000:3000"
depends_on:
- redis
notifications:
image: org/notifications:latest
depends_on:
- redis
postgres:
image: postgres
ports:
- "5432:5432"
• Images from various
repositories

• Can handle databases
Start infrastructure
System overview
API Gateway Notifications service
Client
application
https://https://
Integration test - arrange
import { connectors } from './connectors';
describe('Notifications service', () => {
it('sends and stores notification', async () => {
// Arrange
const api = await connectors.getApiGatewayConnector();
const db = await connectors.getDatabaseConnector();
await db.delete().from('notifications');
...
});
});
Integration test - act
...
// Act
const response = await api({
serviceName: 'notifications',
serviceOperation: 'send',
payload: {
title: 'My notification title',
message: 'My notification message',
}
});
...
Integration test - assert
// Assert
const schema = {
id: expect.any(String),
payload: {
title: 'My notification title',
message: 'My notification message',
}
};
expect(response.status).toEqual(200);
expect(response.json()).toEqual(schema);
expect(await db.from('notifications').count()).toBe(1);
expect(await db.select().from('notifications')).toEqual(schema);
Worth knowing
• Deployment patterns, e.g. serverless

• Decomposition patterns, e.g. DDD subdomains

• Microservice frameworks, e.g. Cote, Moleculer, Seneca

• Security patterns, e.g. access tokens
Thanks!
Any questions?

More Related Content

What's hot

A Pattern Language for Microservices
A Pattern Language for MicroservicesA Pattern Language for Microservices
A Pattern Language for MicroservicesChris Richardson
 
From Monolithic to Microservices
From Monolithic to Microservices From Monolithic to Microservices
From Monolithic to Microservices Amazon Web Services
 
Getting started with Next.js - IM Tech Meetup - Oct 2022.pptx
Getting started with Next.js - IM Tech Meetup - Oct 2022.pptxGetting started with Next.js - IM Tech Meetup - Oct 2022.pptx
Getting started with Next.js - IM Tech Meetup - Oct 2022.pptxIlesh Mistry
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 
Microservices
MicroservicesMicroservices
MicroservicesSmartBear
 
Introduction to OpenID Connect
Introduction to OpenID Connect Introduction to OpenID Connect
Introduction to OpenID Connect Nat Sakimura
 
OAuth2 - Introduction
OAuth2 - IntroductionOAuth2 - Introduction
OAuth2 - IntroductionKnoldus Inc.
 
Building secure applications with keycloak
Building secure applications with keycloak Building secure applications with keycloak
Building secure applications with keycloak Abhishek Koserwal
 
Istio Service Mesh
Istio Service MeshIstio Service Mesh
Istio Service MeshLuke Marsden
 
Microservices Architecture for e-Commerce
Microservices Architecture for e-CommerceMicroservices Architecture for e-Commerce
Microservices Architecture for e-CommerceDivante
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentationThanh Tuong
 
HTML5 WebSocket Introduction
HTML5 WebSocket IntroductionHTML5 WebSocket Introduction
HTML5 WebSocket IntroductionMarcelo Jabali
 
Microservices Architecture & Testing Strategies
Microservices Architecture & Testing StrategiesMicroservices Architecture & Testing Strategies
Microservices Architecture & Testing StrategiesAraf Karsh Hamid
 
Api gateway in microservices
Api gateway in microservicesApi gateway in microservices
Api gateway in microservicesKunal Hire
 

What's hot (20)

A Pattern Language for Microservices
A Pattern Language for MicroservicesA Pattern Language for Microservices
A Pattern Language for Microservices
 
Introduction to Redux
Introduction to ReduxIntroduction to Redux
Introduction to Redux
 
From Monolithic to Microservices
From Monolithic to Microservices From Monolithic to Microservices
From Monolithic to Microservices
 
Getting started with Next.js - IM Tech Meetup - Oct 2022.pptx
Getting started with Next.js - IM Tech Meetup - Oct 2022.pptxGetting started with Next.js - IM Tech Meetup - Oct 2022.pptx
Getting started with Next.js - IM Tech Meetup - Oct 2022.pptx
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
Introduction to microservices
Introduction to microservicesIntroduction to microservices
Introduction to microservices
 
Microservices
MicroservicesMicroservices
Microservices
 
Introduction to OpenID Connect
Introduction to OpenID Connect Introduction to OpenID Connect
Introduction to OpenID Connect
 
OAuth2 - Introduction
OAuth2 - IntroductionOAuth2 - Introduction
OAuth2 - Introduction
 
Building secure applications with keycloak
Building secure applications with keycloak Building secure applications with keycloak
Building secure applications with keycloak
 
Microservice intro
Microservice introMicroservice intro
Microservice intro
 
Istio Service Mesh
Istio Service MeshIstio Service Mesh
Istio Service Mesh
 
Microservices Architecture for e-Commerce
Microservices Architecture for e-CommerceMicroservices Architecture for e-Commerce
Microservices Architecture for e-Commerce
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
Rest web services
Rest web servicesRest web services
Rest web services
 
HTML5 WebSocket Introduction
HTML5 WebSocket IntroductionHTML5 WebSocket Introduction
HTML5 WebSocket Introduction
 
Microservices Architecture & Testing Strategies
Microservices Architecture & Testing StrategiesMicroservices Architecture & Testing Strategies
Microservices Architecture & Testing Strategies
 
DEVSECOPS.pptx
DEVSECOPS.pptxDEVSECOPS.pptx
DEVSECOPS.pptx
 
Api gateway in microservices
Api gateway in microservicesApi gateway in microservices
Api gateway in microservices
 

Similar to Microservices in Node.js: Patterns and techniques

Observability foundations in dynamically evolving architectures
Observability foundations in dynamically evolving architecturesObservability foundations in dynamically evolving architectures
Observability foundations in dynamically evolving architecturesBoyan Dimitrov
 
Building a chat app with windows azure mobile
Building a chat app with windows azure mobileBuilding a chat app with windows azure mobile
Building a chat app with windows azure mobileFlavius-Radu Demian
 
Application Security
Application SecurityApplication Security
Application Securityflorinc
 
FwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsFwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsTimur Shemsedinov
 
Introduction to Distributed Architecture
Introduction to Distributed ArchitectureIntroduction to Distributed Architecture
Introduction to Distributed ArchitectureJustin Weinberg
 
Remote Procedure Call
Remote Procedure CallRemote Procedure Call
Remote Procedure CallNadia Nahar
 
Advanced RingCentral API Use Cases
Advanced RingCentral API Use CasesAdvanced RingCentral API Use Cases
Advanced RingCentral API Use CasesByrne Reese
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfArthyR3
 
Do we need a bigger dev data culture
Do we need a bigger dev data cultureDo we need a bigger dev data culture
Do we need a bigger dev data cultureSimon Dittlmann
 
Resiliency & Security_Ballerina Day CMB 2018
Resiliency & Security_Ballerina Day CMB 2018  Resiliency & Security_Ballerina Day CMB 2018
Resiliency & Security_Ballerina Day CMB 2018 Ballerina
 
Api Statistics- The Scalable Way
Api Statistics- The Scalable WayApi Statistics- The Scalable Way
Api Statistics- The Scalable WayWSO2
 
Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)Tim Burks
 
DevSum'15 : Microsoft Azure and Things
DevSum'15 : Microsoft Azure and ThingsDevSum'15 : Microsoft Azure and Things
DevSum'15 : Microsoft Azure and ThingsThomas Conté
 
Live Streaming & Server Sent Events
Live Streaming & Server Sent EventsLive Streaming & Server Sent Events
Live Streaming & Server Sent Eventstkramar
 
DataStax: 0 to App faster with Ruby and NodeJS
DataStax: 0 to App faster with Ruby and NodeJSDataStax: 0 to App faster with Ruby and NodeJS
DataStax: 0 to App faster with Ruby and NodeJSDataStax Academy
 
Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)danwrong
 
Fiware io t_ul20_cpbr8
Fiware io t_ul20_cpbr8Fiware io t_ul20_cpbr8
Fiware io t_ul20_cpbr8FIWARE
 
Design patterns - ICIN 2010
Design patterns - ICIN 2010Design patterns - ICIN 2010
Design patterns - ICIN 2010steccami
 

Similar to Microservices in Node.js: Patterns and techniques (20)

Observability foundations in dynamically evolving architectures
Observability foundations in dynamically evolving architecturesObservability foundations in dynamically evolving architectures
Observability foundations in dynamically evolving architectures
 
Look, ma! no clients!
Look, ma! no clients!Look, ma! no clients!
Look, ma! no clients!
 
Building a chat app with windows azure mobile
Building a chat app with windows azure mobileBuilding a chat app with windows azure mobile
Building a chat app with windows azure mobile
 
Application Security
Application SecurityApplication Security
Application Security
 
FwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.jsFwDays 2021: Metarhia Technology Stack for Node.js
FwDays 2021: Metarhia Technology Stack for Node.js
 
Introduction to Distributed Architecture
Introduction to Distributed ArchitectureIntroduction to Distributed Architecture
Introduction to Distributed Architecture
 
Remote Procedure Call
Remote Procedure CallRemote Procedure Call
Remote Procedure Call
 
Advanced RingCentral API Use Cases
Advanced RingCentral API Use CasesAdvanced RingCentral API Use Cases
Advanced RingCentral API Use Cases
 
NodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdfNodeJS and ExpressJS.pdf
NodeJS and ExpressJS.pdf
 
Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
Do we need a bigger dev data culture
Do we need a bigger dev data cultureDo we need a bigger dev data culture
Do we need a bigger dev data culture
 
Resiliency & Security_Ballerina Day CMB 2018
Resiliency & Security_Ballerina Day CMB 2018  Resiliency & Security_Ballerina Day CMB 2018
Resiliency & Security_Ballerina Day CMB 2018
 
Api Statistics- The Scalable Way
Api Statistics- The Scalable WayApi Statistics- The Scalable Way
Api Statistics- The Scalable Way
 
Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)Creating Great REST and gRPC API Experiences (in Swift)
Creating Great REST and gRPC API Experiences (in Swift)
 
DevSum'15 : Microsoft Azure and Things
DevSum'15 : Microsoft Azure and ThingsDevSum'15 : Microsoft Azure and Things
DevSum'15 : Microsoft Azure and Things
 
Live Streaming & Server Sent Events
Live Streaming & Server Sent EventsLive Streaming & Server Sent Events
Live Streaming & Server Sent Events
 
DataStax: 0 to App faster with Ruby and NodeJS
DataStax: 0 to App faster with Ruby and NodeJSDataStax: 0 to App faster with Ruby and NodeJS
DataStax: 0 to App faster with Ruby and NodeJS
 
Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)Building @Anywhere (for TXJS)
Building @Anywhere (for TXJS)
 
Fiware io t_ul20_cpbr8
Fiware io t_ul20_cpbr8Fiware io t_ul20_cpbr8
Fiware io t_ul20_cpbr8
 
Design patterns - ICIN 2010
Design patterns - ICIN 2010Design patterns - ICIN 2010
Design patterns - ICIN 2010
 

More from The Software House

Jak kraść miliony, czyli o błędach bezpieczeństwa, które mogą spotkać również...
Jak kraść miliony, czyli o błędach bezpieczeństwa, które mogą spotkać również...Jak kraść miliony, czyli o błędach bezpieczeństwa, które mogą spotkać również...
Jak kraść miliony, czyli o błędach bezpieczeństwa, które mogą spotkać również...The Software House
 
Jak efektywnie podejść do certyfikacji w AWS?
Jak efektywnie podejść do certyfikacji w AWS?Jak efektywnie podejść do certyfikacji w AWS?
Jak efektywnie podejść do certyfikacji w AWS?The Software House
 
O co chodzi z tą dostępnością cyfrową?
O co chodzi z tą dostępnością cyfrową?O co chodzi z tą dostępnością cyfrową?
O co chodzi z tą dostępnością cyfrową?The Software House
 
Chat tekstowy z użyciem Amazon Chime
Chat tekstowy z użyciem Amazon ChimeChat tekstowy z użyciem Amazon Chime
Chat tekstowy z użyciem Amazon ChimeThe Software House
 
Jak nie zwariować z architekturą Serverless?
Jak nie zwariować z architekturą Serverless?Jak nie zwariować z architekturą Serverless?
Jak nie zwariować z architekturą Serverless?The Software House
 
Analiza semantyczna artykułów prasowych w 5 sprintów z użyciem AWS
Analiza semantyczna artykułów prasowych w 5 sprintów z użyciem AWSAnaliza semantyczna artykułów prasowych w 5 sprintów z użyciem AWS
Analiza semantyczna artykułów prasowych w 5 sprintów z użyciem AWSThe Software House
 
Feature flags na ratunek projektu w JavaScript
Feature flags na ratunek projektu w JavaScriptFeature flags na ratunek projektu w JavaScript
Feature flags na ratunek projektu w JavaScriptThe Software House
 
Typowanie nominalne w TypeScript
Typowanie nominalne w TypeScriptTypowanie nominalne w TypeScript
Typowanie nominalne w TypeScriptThe Software House
 
Automatyzacja tworzenia frontendu z wykorzystaniem GraphQL
Automatyzacja tworzenia frontendu z wykorzystaniem GraphQLAutomatyzacja tworzenia frontendu z wykorzystaniem GraphQL
Automatyzacja tworzenia frontendu z wykorzystaniem GraphQLThe Software House
 
Serverless Compose vs hurtownia danych
Serverless Compose vs hurtownia danychServerless Compose vs hurtownia danych
Serverless Compose vs hurtownia danychThe Software House
 
Testy API: połączenie z bazą danych czy implementacja w pamięci
Testy API: połączenie z bazą danych czy implementacja w pamięciTesty API: połączenie z bazą danych czy implementacja w pamięci
Testy API: połączenie z bazą danych czy implementacja w pamięciThe Software House
 
Jak skutecznie read model. Case study
Jak skutecznie read model. Case studyJak skutecznie read model. Case study
Jak skutecznie read model. Case studyThe Software House
 
Firestore czyli ognista baza od giganta z Doliny Krzemowej
Firestore czyli ognista baza od giganta z Doliny KrzemowejFirestore czyli ognista baza od giganta z Doliny Krzemowej
Firestore czyli ognista baza od giganta z Doliny KrzemowejThe Software House
 
Jak utrzymać stado Lambd w ryzach
Jak utrzymać stado Lambd w ryzachJak utrzymać stado Lambd w ryzach
Jak utrzymać stado Lambd w ryzachThe Software House
 
O łączeniu Storyblok i Next.js
O łączeniu Storyblok i Next.jsO łączeniu Storyblok i Next.js
O łączeniu Storyblok i Next.jsThe Software House
 
Amazon Step Functions. Sposób na implementację procesów w chmurze
Amazon Step Functions. Sposób na implementację procesów w chmurzeAmazon Step Functions. Sposób na implementację procesów w chmurze
Amazon Step Functions. Sposób na implementację procesów w chmurzeThe Software House
 
Od Figmy do gotowej aplikacji bez linijki kodu
Od Figmy do gotowej aplikacji bez linijki koduOd Figmy do gotowej aplikacji bez linijki kodu
Od Figmy do gotowej aplikacji bez linijki koduThe Software House
 

More from The Software House (20)

Jak kraść miliony, czyli o błędach bezpieczeństwa, które mogą spotkać również...
Jak kraść miliony, czyli o błędach bezpieczeństwa, które mogą spotkać również...Jak kraść miliony, czyli o błędach bezpieczeństwa, które mogą spotkać również...
Jak kraść miliony, czyli o błędach bezpieczeństwa, które mogą spotkać również...
 
Uszanowanko Podsumowanko
Uszanowanko PodsumowankoUszanowanko Podsumowanko
Uszanowanko Podsumowanko
 
Jak efektywnie podejść do certyfikacji w AWS?
Jak efektywnie podejść do certyfikacji w AWS?Jak efektywnie podejść do certyfikacji w AWS?
Jak efektywnie podejść do certyfikacji w AWS?
 
O co chodzi z tą dostępnością cyfrową?
O co chodzi z tą dostępnością cyfrową?O co chodzi z tą dostępnością cyfrową?
O co chodzi z tą dostępnością cyfrową?
 
Chat tekstowy z użyciem Amazon Chime
Chat tekstowy z użyciem Amazon ChimeChat tekstowy z użyciem Amazon Chime
Chat tekstowy z użyciem Amazon Chime
 
Migracje danych serverless
Migracje danych serverlessMigracje danych serverless
Migracje danych serverless
 
Jak nie zwariować z architekturą Serverless?
Jak nie zwariować z architekturą Serverless?Jak nie zwariować z architekturą Serverless?
Jak nie zwariować z architekturą Serverless?
 
Analiza semantyczna artykułów prasowych w 5 sprintów z użyciem AWS
Analiza semantyczna artykułów prasowych w 5 sprintów z użyciem AWSAnaliza semantyczna artykułów prasowych w 5 sprintów z użyciem AWS
Analiza semantyczna artykułów prasowych w 5 sprintów z użyciem AWS
 
Feature flags na ratunek projektu w JavaScript
Feature flags na ratunek projektu w JavaScriptFeature flags na ratunek projektu w JavaScript
Feature flags na ratunek projektu w JavaScript
 
Typowanie nominalne w TypeScript
Typowanie nominalne w TypeScriptTypowanie nominalne w TypeScript
Typowanie nominalne w TypeScript
 
Automatyzacja tworzenia frontendu z wykorzystaniem GraphQL
Automatyzacja tworzenia frontendu z wykorzystaniem GraphQLAutomatyzacja tworzenia frontendu z wykorzystaniem GraphQL
Automatyzacja tworzenia frontendu z wykorzystaniem GraphQL
 
Serverless Compose vs hurtownia danych
Serverless Compose vs hurtownia danychServerless Compose vs hurtownia danych
Serverless Compose vs hurtownia danych
 
Testy API: połączenie z bazą danych czy implementacja w pamięci
Testy API: połączenie z bazą danych czy implementacja w pamięciTesty API: połączenie z bazą danych czy implementacja w pamięci
Testy API: połączenie z bazą danych czy implementacja w pamięci
 
Jak skutecznie read model. Case study
Jak skutecznie read model. Case studyJak skutecznie read model. Case study
Jak skutecznie read model. Case study
 
Firestore czyli ognista baza od giganta z Doliny Krzemowej
Firestore czyli ognista baza od giganta z Doliny KrzemowejFirestore czyli ognista baza od giganta z Doliny Krzemowej
Firestore czyli ognista baza od giganta z Doliny Krzemowej
 
Jak utrzymać stado Lambd w ryzach
Jak utrzymać stado Lambd w ryzachJak utrzymać stado Lambd w ryzach
Jak utrzymać stado Lambd w ryzach
 
Jak poskromić AWS?
Jak poskromić AWS?Jak poskromić AWS?
Jak poskromić AWS?
 
O łączeniu Storyblok i Next.js
O łączeniu Storyblok i Next.jsO łączeniu Storyblok i Next.js
O łączeniu Storyblok i Next.js
 
Amazon Step Functions. Sposób na implementację procesów w chmurze
Amazon Step Functions. Sposób na implementację procesów w chmurzeAmazon Step Functions. Sposób na implementację procesów w chmurze
Amazon Step Functions. Sposób na implementację procesów w chmurze
 
Od Figmy do gotowej aplikacji bez linijki kodu
Od Figmy do gotowej aplikacji bez linijki koduOd Figmy do gotowej aplikacji bez linijki kodu
Od Figmy do gotowej aplikacji bez linijki kodu
 

Recently uploaded

Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.soniya singh
 
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Networking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOGNetworking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOGAPNIC
 
Radiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsRadiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsstephieert
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130  Available With RoomVIP Kolkata Call Girl Alambazar 👉 8250192130  Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Roomdivyansh0kumar0
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirtrahman018755
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Standkumarajju5765
 
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...SofiyaSharma5
 
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts servicevipmodelshub1
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024APNIC
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607dollysharma2066
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)Damian Radcliffe
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkataanamikaraghav4
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...tanu pandey
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersDamian Radcliffe
 
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceDelhi Call girls
 

Recently uploaded (20)

Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
Call Now ☎ 8264348440 !! Call Girls in Shahpur Jat Escort Service Delhi N.C.R.
 
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
Dwarka Sector 26 Call Girls | Delhi | 9999965857 🫦 Vanshika Verma More Our Se...
 
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Sukhdev Vihar Delhi 💯Call Us 🔝8264348440🔝
 
Networking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOGNetworking in the Penumbra presented by Geoff Huston at NZNOG
Networking in the Penumbra presented by Geoff Huston at NZNOG
 
Radiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girlsRadiant Call girls in Dubai O56338O268 Dubai Call girls
Radiant Call girls in Dubai O56338O268 Dubai Call girls
 
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
Call Girls In Saket Delhi 💯Call Us 🔝8264348440🔝
 
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130  Available With RoomVIP Kolkata Call Girl Alambazar 👉 8250192130  Available With Room
VIP Kolkata Call Girl Alambazar 👉 8250192130 Available With Room
 
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya ShirtChallengers I Told Ya Shirt
Challengers I Told Ya ShirtChallengers I Told Ya Shirt
 
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night StandHot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
Hot Call Girls |Delhi |Hauz Khas ☎ 9711199171 Book Your One night Stand
 
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
Low Rate Young Call Girls in Sector 63 Mamura Noida ✔️☆9289244007✔️☆ Female E...
 
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts serviceChennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
Chennai Call Girls Alwarpet Phone 🍆 8250192130 👅 celebrity escorts service
 
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls KolkataRussian Call Girls in Kolkata Ishita 🤌  8250192130 🚀 Vip Call Girls Kolkata
Russian Call Girls in Kolkata Ishita 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
DDoS In Oceania and the Pacific, presented by Dave Phelan at NZNOG 2024
 
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No AdvanceRohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
Rohini Sector 22 Call Girls Delhi 9999965857 @Sabina Saikh No Advance
 
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
FULL ENJOY Call Girls In Mayur Vihar Delhi Contact Us 8377087607
 
How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)How is AI changing journalism? (v. April 2024)
How is AI changing journalism? (v. April 2024)
 
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls KolkataLow Rate Call Girls Kolkata Avani 🤌  8250192130 🚀 Vip Call Girls Kolkata
Low Rate Call Girls Kolkata Avani 🤌 8250192130 🚀 Vip Call Girls Kolkata
 
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...Pune Airport ( Call Girls ) Pune  6297143586  Hot Model With Sexy Bhabi Ready...
Pune Airport ( Call Girls ) Pune 6297143586 Hot Model With Sexy Bhabi Ready...
 
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providersMoving Beyond Twitter/X and Facebook - Social Media for local news providers
Moving Beyond Twitter/X and Facebook - Social Media for local news providers
 
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort ServiceEnjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
Enjoy Night⚡Call Girls Dlf City Phase 3 Gurgaon >༒8448380779 Escort Service
 

Microservices in Node.js: Patterns and techniques

  • 1. Microservices in Mariusz Richtscheid Gliwice, 10.10.2018 patterns and techniques
  • 2. About me • Full-Stack Developer in The Software House • richtscheid@gmail.com • linkedin.com/in/richtscheid • github.com/barograf Mariusz Richtscheid
  • 3. Agenda • Why microservices? • Communication patterns • Data management patterns • Reliability and observability patterns • Testing
  • 4. Monolith • Can be difficult to understand and modify • Development and deployments slow down over time • Modularity breaks down over time • Quality of the code declines over time • It is hard to change technology stack
  • 5. Why microservices? • Smaller services are easier to understand and test • Services can be deployed more frequently • Development in multiple teams • Improved fault isolation • Every service can have different technology stack
  • 6. A lot of issues to address How to decompose into services? How to deploy? How to handle configs, logging, tracing, health checks, metrics? How to communicate between services? How do external clients communicate with the services? What about service discovery? How to prevent failures? How to maintain data consistency? How to handle security? How to test it? How to troubleshoot problems? How to display data from multiple services?
  • 9. API Gateway overview Service 1 Service 2 API GatewayClient Service 3 System Client ✔ ❌
  • 10. API Gateway • One entry point for the entire system • Handles security - other services communicate freely • Knows how to call other services - statically defined or with service discovery • Should not contain business logic
  • 11. API Gateway - message format export interface ISocketMessage { serviceName: string; serviceOperation: string; payload: object; }
  • 12. API Gateway - handling requests client.on('message', (data: ISocketMessage) => { this.services[data.serviceName][data.serviceOperation]({ ...data.payload }) .then(result => { client.emit('message', { payload: result }); }) .catch(error => { /* please log me */ }); });
  • 14. Service discovery Router Service registry Service 1 RegisterGet address Request Service 2 Request
  • 15. • Solution to connect and configure applications across distributed infrastructure • Service discovery • Health checking • Provides useful UI
  • 16. Consul UI - services
  • 17. Consul UI - health checks
  • 19. Health check endpoint const app = express(); app.get('/health', (req, res) => { res.status(200); res.send('ok'); res.end(); });
  • 20. Service and health check registration const consul = require('consul')(); consul.agent.service.register({ name: 'api-gateway', address: process.env.HOST, port: Number(process.env.PORT), check: { http: `http://${process.env.HOST}:${process.env.PORT}/health`, interval: '30s', } }, err => { if (err) throw err });
  • 21. Health check subscription consul .watch({ method: consul.health.service, options: { service: 'translations' } }) .on('change', function (data, res) { const status = data[0].Checks[1].Status; console.log(`translations service status: ${status}`); });
  • 24. Remote procedure invocation API GatewayClient System Service 1 Service 2 https:// Apache Thrift
  • 25. Message broker API GatewayClient Service 1 Message broker Service 2 Pub/Sub • Loose coupling • Buffering messages
  • 27. Shared database Service 1 API GatewayClient Service 2 System Shared database
  • 28. Database per service Service 1 API GatewayClient Service 2 System Service 1 database Service 2 database • Scaling • Data consistency • Queries
  • 30. Saga • A service which coordinates sequence of local transactions across multiple microservices • Each local transaction updates the database • If local transaction fails then the saga executes a rollback for all related microservices
  • 31. Rollback in saga Service 1 Operation 1 Operation 2 Operation 3 Saga Service 2 Service 3 Service 4 ❌ ✅ ✅ Service 4Rollback✅ Error Data changed Data changed
  • 32. Querying - API Composition
  • 33. API Composition API GatewayClient Service 1 System Query Query Query Service 2 Service 3 Service 4
  • 35. Circuit breaker • Mechanism for fast fail of requests towards unhealthy services • Prevents unnecessary traffic and cascading fails • Unhealthy services can recover safely
  • 36. Circuit breaker Service 2 API GatewayClient Service 1 System Service 1 Error
  • 38. Distributed tracing • Logging is not enough in distributed system • Tracing gives insight into code execution across services • With tracing we know what, where and when something fails
  • 39. Distributed tracing overview Service 2 API GatewayClient Tracing server Service 1 System Tracing ID (e.g. header) Tracing ID
  • 40. • Standard for distributed tracing • Defines interfaces and data model for many programming languages • Has no real implementation
  • 41. • OpenTracing compatible implementation for distributed tracing • Released as open source by Uber Technologies • Available in Node, Go, Java, Python and C++ • Provides useful UI
  • 43. Jaeger UI - trace details Span
  • 44. Jaeger UI - span details
  • 46. Initializing tracer import { initTracer } from 'jaeger-client'; const tracer = initTracer( { serviceName: process.env.APP_NAME || 'Unknown app', sampler: { type: 'const', param: 1, }, reporter: { logSpans: true, agentHost: process.env.TRACING_SERVICE_HOST || 'localhost', agentPort: Number(process.env.TRACING_SERVICE_PORT) || 6832, }, }, { logger } );
  • 47. Creating new span const span = tracer.startSpan('name of the span'); span.addTags({ type: 'foo' }); /* some code */ span.finish();
  • 48. Sending tracing ID import { FORMAT_HTTP_HEADERS } from 'opentracing'; const headers = {}; tracer.inject(span, FORMAT_HTTP_HEADERS, headers); const tracingId = JSON.stringify(headers); /* send tracing ID to other service (with headers, as string value etc.) */
  • 49. Receiving tracing ID /* receive tracing ID from other service */ const tracingIdString = '{"uber-trace-id":"d7ee8bcc3f4a1033:d7ee8bcc3f4a1033:0:1"}'; const spanFromOtherService = tracer.extract( FORMAT_HTTP_HEADERS, JSON.parse(tracingIdString) ); const span = tracer.startSpan('name of the span', { childOf: spanFromOtherService }); /* some code */ span.finish();
  • 51. Testing • Specs are not enough • Write integration tests for parts of your infrastructure • Run your infrastructure with one command • Can be achieved with Docker Compose or PM2 ecosystem • Different definitions for different parts of infrastructure
  • 52. PM2 - ecosystem.json { "apps": [ { "name": "API Gateway", "script": "index.ts", "cwd": "src/services/api-gateway" }, { "name": "Notifications service", "script": "index.ts", "cwd": "src/services/notifications" } ] } • Requires mono-repository • For Node scripts only
  • 53. docker-compose.yml version: '3' services: api-gateway: image: org/api-gateway:latest ports: - "3000:3000" depends_on: - redis notifications: image: org/notifications:latest depends_on: - redis postgres: image: postgres ports: - "5432:5432" • Images from various repositories • Can handle databases
  • 55. System overview API Gateway Notifications service Client application https://https://
  • 56. Integration test - arrange import { connectors } from './connectors'; describe('Notifications service', () => { it('sends and stores notification', async () => { // Arrange const api = await connectors.getApiGatewayConnector(); const db = await connectors.getDatabaseConnector(); await db.delete().from('notifications'); ... }); });
  • 57. Integration test - act ... // Act const response = await api({ serviceName: 'notifications', serviceOperation: 'send', payload: { title: 'My notification title', message: 'My notification message', } }); ...
  • 58. Integration test - assert // Assert const schema = { id: expect.any(String), payload: { title: 'My notification title', message: 'My notification message', } }; expect(response.status).toEqual(200); expect(response.json()).toEqual(schema); expect(await db.from('notifications').count()).toBe(1); expect(await db.select().from('notifications')).toEqual(schema);
  • 59. Worth knowing • Deployment patterns, e.g. serverless • Decomposition patterns, e.g. DDD subdomains • Microservice frameworks, e.g. Cote, Moleculer, Seneca • Security patterns, e.g. access tokens