SlideShare a Scribd company logo
1 of 36
Download to read offline
Lucas Cavalcanti

@lucascs
Microservices in
Clojure
Context
Microservices
~80 Clojure services
~60 engineers
~10 teams
3.5 years old
OOP
Objects, the mainstream abstraction
Image @ http://www.eduardopires.net.br/2015/01/solid-teoria-e-pratica/
What about Functional Programming?
SÃO PAULO, BRASIL
TABLE OF CONTENTS
Immutability
Components
Pure Functions
Schemas
Ports and Adapters
SÃO PAULO, BRASIL
Immutability
SOUTHEAST BRAZIL REGION FROM SPACE
Immutability
Definition
“If I’m given a value, it’s guaranteed that it won’t ever change”
Technology choices
Immutability
Clojure
Immutability
All default data structures are immutable:
-Maps, Lists, Sets
-Records
Mutability is explicit: atoms/refs @, dynamic vars *…*
Datomic
Immutability
Datomic stores the changes/transactions, not just the
data
-append only
-db as a value
-everything is data (transaction, schema, entities)
Kafka
Immutability
Persistent Queues/Topics
-each consumer has its offset
-ability to replay messages
AWS + Docker
Immutability
Ability to spin machines with a given image/
configuration
-Each build generates a docker image
-Each deploy spins a new machine with the new
version
-As soon as the new version is healthy, old version is
killed. (blue-green deployment)
Components
SOUTHEAST BRAZIL REGION FROM SPACE
Components
https://github.com/stuartsierra/component
(defprotocol Database

(query [this query-str]))



(defrecord SomeDatabase [config-1 config-2 other-components]

component/Lifecycle

(start [this]

(assoc this :connection (connect! config-1 config-2 other-components)))



(stop [this]

(release! (:connection this))

(dissoc this :connection))



Database

(query [this query-str] (do-query! (:connection this) query-str)))
System map
Components
{:database #SomeDatabase{...}

:http-client #HttpClient{...}

:kafka #Kafka{...}

:auth #AuthCredentials{...}

...}
-Created at startup
-Entrypoints (e.g http server or kafka consumers) have access to all
components the business flows need
-dependencies of a given flow are threaded from the entry point until
the end, one by one if possible
-Thus no static access to system map! (e.g via a global atom)
-Any resemblance to objects and classes is just coincidence ;)
Pure functions
SOUTHEAST BRAZIL REGION FROM SPACE
Pure functions
Definition
"Given the same inputs, it will always produce the same output"
Simplicity
Pure functions
-easier to reason about, fewer moving pieces
-easier to test, less need for mocking values
-parallelizable by default, no need for locks or STMs
Datomic
Pure functions
-Datomic’s db as a value allows us to consider a function
that queries the database as a pure function
-db is a snapshot of the database at a certain point in time.
-So, querying the same db instance will always produce the
same result
Impure functions
Pure functions
-functions that produce side effects should be marked as
such. We use `!` at the end.
-split code which handles and transforms data from code
that handles side effects
-should be moved to the borders of the flow, if possible
-Consider returning a future/promise like value, so side
effect results can be composed (e.g with manifold or
finagle)
https://github.com/ztellman/manifold
https://github.com/twitter/finagle
Schema/Spec
SOUTHEAST BRAZIL REGION FROM SPACE
Schema
Legacy
Majority of our code base was written before clojure.spec existed,
so I’ll be talking about the Schema library instead. Most principles
apply to clojure.spec as well.
Schema/Spec
Documentation
-Clojure doesn’t force you to write types
-parameter names are not enough
-declaring types helps a lot when glancing at the function
-values can be verified against a schema
Function declaration
Schema/spec
-All pure functions declare schemas for parameters and
return value
-All impure functions declare for parameters and don’t
declare output type if it’s not relevant.
-Validated at runtime in dev/test environments, on every
function call
-Validation is off on production.
Wire formats
Schema/Spec
-Internal schemas are your domain models
-Wire schemas are how you expose data to other services/
clients
-If they are different, you can evolve internal schemas
without breaking clients
-Need an adapter layer
-wire schemas are always validated on entry/exit points,
specially in production
-single repository for all wire schemas (for all 60+ services)
-caveat: this repository has a really high churn. Beware
Growing Schemas
Spec-ulation
Please watch Rich Hickey’s talk at Clojure Conj 2016
Spec-ulation:
https://www.youtube.com/watch?v=oyLBGkS5ICk
Ports and Adapters
(a.k.a Hexagonal Architecture)
SOUTHEAST BRAZIL REGION FROM SPACE
Ports and Adapters
Definition
Core logic is independent to how we can call it (yellow)
A port is an entry-point of the application (blue)
An adapter is the bridge between a port and the core logic (red)
http://www.dossier-andreas.net/software_architecture/ports_and_adapters.html
http://alistair.cockburn.us/Hexagonal+architecture
Ports and Adapters (Nubank version)
Extended Definition
Pure business logic (green)
Controller logic wires the flow between the ports (yellow)
A port is an entry-point of the application (blue)
An adapter is the bridge between a port and the core logic (red)
Ports (Components)
Ports and Adapters
-Ports are initialised at startup
-Each port has a corresponding
component
-Serializes data to a transport
format (e.g JSON, Transit)
-Usually library code shared by
all services
-Tested via integration tests
HTTP
Kafka
Datomic
File Storage
Metrics
E-mail
Adapters (Diplomat)
Ports and Adapters
-Adapters are the interface to
ports
-Contain HTTP and Kafka
consumer handlers
-Adapt wire schema to
internal schema
-Calls and is called by
controller functions
-Tested with fake versions of
the port components, or
mocks
HTTP
Kafka
Datomic
File Storage
Metrics
E-mail
Controllers
Ports and Adapters
-Controllers wires the flow
between entry-point and the
side effects
-Only deals with internal
schemas
-Delegates business logic to
pure functions
-Composes side effect results
-Tested mostly with mocks
HTTP
Kafka
Datomic
File Storage
Metrics
E-mail
Business Logic
Ports and Adapters
-Handles and transforms
immutable data
-Pure functions
-Best place to enforce
invariants and type checks
(e.g using clojure.spec)
-Can be tested using
generative testing
-Should be the largest part of
the application
HTTP
Kafka
Datomic
File Storage
Metrics
E-mail
Microservices
Ports and Adapters
-Each service follows about
the same design
-Services communicate with
each other using one of the
ports (e.g HTTP or Kafka)
-Services DON’T share
databases
-HTTP responses contain
hypermedia, so we can
replace a service without
having to change clients
-Tested with end to end tests,
with all services deployed
Clojure is simple
Keep your design simple
Keep your architecture simple
SÃO PAULO, BRASIL
Lucas Cavalcanti

@lucascs
Thank you

More Related Content

What's hot

고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들Chris Ohk
 
Arquitetura funcional em microservices, 4 anos depois
Arquitetura funcional em microservices, 4 anos depoisArquitetura funcional em microservices, 4 anos depois
Arquitetura funcional em microservices, 4 anos depoisLucas Cavalcanti dos Santos
 
High Concurrency Architecture at TIKI
High Concurrency Architecture at TIKIHigh Concurrency Architecture at TIKI
High Concurrency Architecture at TIKINghia Minh
 
Data Streaming in Big Data Analysis
Data Streaming in Big Data AnalysisData Streaming in Big Data Analysis
Data Streaming in Big Data AnalysisVincenzo Gulisano
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Scott Wlaschin
 
Building zero data loss pipelines with apache kafka
Building zero data loss pipelines with apache kafkaBuilding zero data loss pipelines with apache kafka
Building zero data loss pipelines with apache kafkaAvinash Ramineni
 
파이썬 데이터베이스 연결 2탄
파이썬 데이터베이스 연결 2탄파이썬 데이터베이스 연결 2탄
파이썬 데이터베이스 연결 2탄SeongHyun Ahn
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDBvaluebound
 
Presentation citrix internals ica connectivity
Presentation   citrix internals ica connectivityPresentation   citrix internals ica connectivity
Presentation citrix internals ica connectivityxKinAnx
 
Fighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with EmbulkFighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with EmbulkSadayuki Furuhashi
 
11st Legacy Application의 Spring Cloud 기반 MicroServices로 전환 개발 사례
11st Legacy Application의 Spring Cloud 기반 MicroServices로 전환 개발 사례11st Legacy Application의 Spring Cloud 기반 MicroServices로 전환 개발 사례
11st Legacy Application의 Spring Cloud 기반 MicroServices로 전환 개발 사례YongSung Yoon
 
Integrating Public & Private Clouds
Integrating Public & Private CloudsIntegrating Public & Private Clouds
Integrating Public & Private CloudsProact Belgium
 
Stability Patterns for Microservices
Stability Patterns for MicroservicesStability Patterns for Microservices
Stability Patterns for Microservicespflueras
 
Distributed Transaction in Microservice
Distributed Transaction in MicroserviceDistributed Transaction in Microservice
Distributed Transaction in MicroserviceNghia Minh
 

What's hot (20)

고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
고려대학교 컴퓨터학과 특강 - 대학생 때 알았더라면 좋았을 것들
 
Arquitetura funcional em microservices, 4 anos depois
Arquitetura funcional em microservices, 4 anos depoisArquitetura funcional em microservices, 4 anos depois
Arquitetura funcional em microservices, 4 anos depois
 
High Concurrency Architecture at TIKI
High Concurrency Architecture at TIKIHigh Concurrency Architecture at TIKI
High Concurrency Architecture at TIKI
 
Data Streaming in Big Data Analysis
Data Streaming in Big Data AnalysisData Streaming in Big Data Analysis
Data Streaming in Big Data Analysis
 
Data models in NoSQL
Data models in NoSQLData models in NoSQL
Data models in NoSQL
 
Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)Functional Programming Patterns (BuildStuff '14)
Functional Programming Patterns (BuildStuff '14)
 
Building zero data loss pipelines with apache kafka
Building zero data loss pipelines with apache kafkaBuilding zero data loss pipelines with apache kafka
Building zero data loss pipelines with apache kafka
 
Introduction to Rust
Introduction to RustIntroduction to Rust
Introduction to Rust
 
파이썬 데이터베이스 연결 2탄
파이썬 데이터베이스 연결 2탄파이썬 데이터베이스 연결 2탄
파이썬 데이터베이스 연결 2탄
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDB
 
Presentation citrix internals ica connectivity
Presentation   citrix internals ica connectivityPresentation   citrix internals ica connectivity
Presentation citrix internals ica connectivity
 
Apache CouchDB
Apache CouchDBApache CouchDB
Apache CouchDB
 
Fighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with EmbulkFighting Against Chaotically Separated Values with Embulk
Fighting Against Chaotically Separated Values with Embulk
 
11st Legacy Application의 Spring Cloud 기반 MicroServices로 전환 개발 사례
11st Legacy Application의 Spring Cloud 기반 MicroServices로 전환 개발 사례11st Legacy Application의 Spring Cloud 기반 MicroServices로 전환 개발 사례
11st Legacy Application의 Spring Cloud 기반 MicroServices로 전환 개발 사례
 
Integrating Public & Private Clouds
Integrating Public & Private CloudsIntegrating Public & Private Clouds
Integrating Public & Private Clouds
 
Serving ML easily with FastAPI - meme version
Serving ML easily with FastAPI - meme versionServing ML easily with FastAPI - meme version
Serving ML easily with FastAPI - meme version
 
Stability Patterns for Microservices
Stability Patterns for MicroservicesStability Patterns for Microservices
Stability Patterns for Microservices
 
Distributed Transaction in Microservice
Distributed Transaction in MicroserviceDistributed Transaction in Microservice
Distributed Transaction in Microservice
 
Introducing Akka
Introducing AkkaIntroducing Akka
Introducing Akka
 
Consistency in NoSQL
Consistency in NoSQLConsistency in NoSQL
Consistency in NoSQL
 

Similar to Microservices in Clojure

Golden Gate - How to start such a project?
Golden Gate  - How to start such a project?Golden Gate  - How to start such a project?
Golden Gate - How to start such a project?Trivadis
 
A sane approach to microservices
A sane approach to microservicesA sane approach to microservices
A sane approach to microservicesToby Matejovsky
 
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...Guido Schmutz
 
Data Summer Conf 2018, “Building unified Batch and Stream processing pipeline...
Data Summer Conf 2018, “Building unified Batch and Stream processing pipeline...Data Summer Conf 2018, “Building unified Batch and Stream processing pipeline...
Data Summer Conf 2018, “Building unified Batch and Stream processing pipeline...Provectus
 
Impact 2014 - IIB - selecting the right transformation option
Impact 2014 -  IIB - selecting the right transformation optionImpact 2014 -  IIB - selecting the right transformation option
Impact 2014 - IIB - selecting the right transformation optionAndrew Coleman
 
Porting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustPorting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustEvan Chan
 
PuppetDB: Sneaking Clojure into Operations
PuppetDB: Sneaking Clojure into OperationsPuppetDB: Sneaking Clojure into Operations
PuppetDB: Sneaking Clojure into Operationsgrim_radical
 
Technology Stack Discussion
Technology Stack DiscussionTechnology Stack Discussion
Technology Stack DiscussionZaiyang Li
 
Deep dive into the native multi model database ArangoDB
Deep dive into the native multi model database ArangoDBDeep dive into the native multi model database ArangoDB
Deep dive into the native multi model database ArangoDBArangoDB Database
 
Spark (Structured) Streaming vs. Kafka Streams
Spark (Structured) Streaming vs. Kafka StreamsSpark (Structured) Streaming vs. Kafka Streams
Spark (Structured) Streaming vs. Kafka StreamsGuido Schmutz
 
Next-Generation Completeness and Consistency Management in the Digital Threa...
Next-Generation Completeness and Consistency Management in the Digital Threa...Next-Generation Completeness and Consistency Management in the Digital Threa...
Next-Generation Completeness and Consistency Management in the Digital Threa...Ákos Horváth
 
Kamailio with Docker and Kubernetes
Kamailio with Docker and KubernetesKamailio with Docker and Kubernetes
Kamailio with Docker and KubernetesPaolo Visintin
 
byteLAKE's Alveo FPGA Solutions
byteLAKE's Alveo FPGA SolutionsbyteLAKE's Alveo FPGA Solutions
byteLAKE's Alveo FPGA SolutionsbyteLAKE
 
Machine learning at scale challenges and solutions
Machine learning at scale challenges and solutionsMachine learning at scale challenges and solutions
Machine learning at scale challenges and solutionsStavros Kontopoulos
 
LarKC Tutorial at ISWC 2009 - Introduction
LarKC Tutorial at ISWC 2009 - IntroductionLarKC Tutorial at ISWC 2009 - Introduction
LarKC Tutorial at ISWC 2009 - IntroductionLarKC
 
Materialize: a platform for changing data
Materialize: a platform for changing dataMaterialize: a platform for changing data
Materialize: a platform for changing dataAltinity Ltd
 
Hands on with CoAP and Californium
Hands on with CoAP and CaliforniumHands on with CoAP and Californium
Hands on with CoAP and CaliforniumJulien Vermillard
 
Functional web with clojure
Functional web with clojureFunctional web with clojure
Functional web with clojureJohn Stevenson
 
Introduction to Structured Streaming
Introduction to Structured StreamingIntroduction to Structured Streaming
Introduction to Structured StreamingKnoldus Inc.
 
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...Guido Schmutz
 

Similar to Microservices in Clojure (20)

Golden Gate - How to start such a project?
Golden Gate  - How to start such a project?Golden Gate  - How to start such a project?
Golden Gate - How to start such a project?
 
A sane approach to microservices
A sane approach to microservicesA sane approach to microservices
A sane approach to microservices
 
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
 
Data Summer Conf 2018, “Building unified Batch and Stream processing pipeline...
Data Summer Conf 2018, “Building unified Batch and Stream processing pipeline...Data Summer Conf 2018, “Building unified Batch and Stream processing pipeline...
Data Summer Conf 2018, “Building unified Batch and Stream processing pipeline...
 
Impact 2014 - IIB - selecting the right transformation option
Impact 2014 -  IIB - selecting the right transformation optionImpact 2014 -  IIB - selecting the right transformation option
Impact 2014 - IIB - selecting the right transformation option
 
Porting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to RustPorting a Streaming Pipeline from Scala to Rust
Porting a Streaming Pipeline from Scala to Rust
 
PuppetDB: Sneaking Clojure into Operations
PuppetDB: Sneaking Clojure into OperationsPuppetDB: Sneaking Clojure into Operations
PuppetDB: Sneaking Clojure into Operations
 
Technology Stack Discussion
Technology Stack DiscussionTechnology Stack Discussion
Technology Stack Discussion
 
Deep dive into the native multi model database ArangoDB
Deep dive into the native multi model database ArangoDBDeep dive into the native multi model database ArangoDB
Deep dive into the native multi model database ArangoDB
 
Spark (Structured) Streaming vs. Kafka Streams
Spark (Structured) Streaming vs. Kafka StreamsSpark (Structured) Streaming vs. Kafka Streams
Spark (Structured) Streaming vs. Kafka Streams
 
Next-Generation Completeness and Consistency Management in the Digital Threa...
Next-Generation Completeness and Consistency Management in the Digital Threa...Next-Generation Completeness and Consistency Management in the Digital Threa...
Next-Generation Completeness and Consistency Management in the Digital Threa...
 
Kamailio with Docker and Kubernetes
Kamailio with Docker and KubernetesKamailio with Docker and Kubernetes
Kamailio with Docker and Kubernetes
 
byteLAKE's Alveo FPGA Solutions
byteLAKE's Alveo FPGA SolutionsbyteLAKE's Alveo FPGA Solutions
byteLAKE's Alveo FPGA Solutions
 
Machine learning at scale challenges and solutions
Machine learning at scale challenges and solutionsMachine learning at scale challenges and solutions
Machine learning at scale challenges and solutions
 
LarKC Tutorial at ISWC 2009 - Introduction
LarKC Tutorial at ISWC 2009 - IntroductionLarKC Tutorial at ISWC 2009 - Introduction
LarKC Tutorial at ISWC 2009 - Introduction
 
Materialize: a platform for changing data
Materialize: a platform for changing dataMaterialize: a platform for changing data
Materialize: a platform for changing data
 
Hands on with CoAP and Californium
Hands on with CoAP and CaliforniumHands on with CoAP and Californium
Hands on with CoAP and Californium
 
Functional web with clojure
Functional web with clojureFunctional web with clojure
Functional web with clojure
 
Introduction to Structured Streaming
Introduction to Structured StreamingIntroduction to Structured Streaming
Introduction to Structured Streaming
 
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
Spark (Structured) Streaming vs. Kafka Streams - two stream processing platfo...
 

Recently uploaded

Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
 

Recently uploaded (20)

Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
 

Microservices in Clojure

  • 2. Context Microservices ~80 Clojure services ~60 engineers ~10 teams 3.5 years old
  • 3. OOP Objects, the mainstream abstraction Image @ http://www.eduardopires.net.br/2015/01/solid-teoria-e-pratica/
  • 4. What about Functional Programming? SÃO PAULO, BRASIL
  • 5. TABLE OF CONTENTS Immutability Components Pure Functions Schemas Ports and Adapters SÃO PAULO, BRASIL
  • 7. Immutability Definition “If I’m given a value, it’s guaranteed that it won’t ever change”
  • 9. Clojure Immutability All default data structures are immutable: -Maps, Lists, Sets -Records Mutability is explicit: atoms/refs @, dynamic vars *…*
  • 10. Datomic Immutability Datomic stores the changes/transactions, not just the data -append only -db as a value -everything is data (transaction, schema, entities)
  • 11. Kafka Immutability Persistent Queues/Topics -each consumer has its offset -ability to replay messages
  • 12. AWS + Docker Immutability Ability to spin machines with a given image/ configuration -Each build generates a docker image -Each deploy spins a new machine with the new version -As soon as the new version is healthy, old version is killed. (blue-green deployment)
  • 14. Components https://github.com/stuartsierra/component (defprotocol Database
 (query [this query-str]))
 
 (defrecord SomeDatabase [config-1 config-2 other-components]
 component/Lifecycle
 (start [this]
 (assoc this :connection (connect! config-1 config-2 other-components)))
 
 (stop [this]
 (release! (:connection this))
 (dissoc this :connection))
 
 Database
 (query [this query-str] (do-query! (:connection this) query-str)))
  • 15. System map Components {:database #SomeDatabase{...}
 :http-client #HttpClient{...}
 :kafka #Kafka{...}
 :auth #AuthCredentials{...}
 ...} -Created at startup -Entrypoints (e.g http server or kafka consumers) have access to all components the business flows need -dependencies of a given flow are threaded from the entry point until the end, one by one if possible -Thus no static access to system map! (e.g via a global atom) -Any resemblance to objects and classes is just coincidence ;)
  • 16. Pure functions SOUTHEAST BRAZIL REGION FROM SPACE
  • 17. Pure functions Definition "Given the same inputs, it will always produce the same output"
  • 18. Simplicity Pure functions -easier to reason about, fewer moving pieces -easier to test, less need for mocking values -parallelizable by default, no need for locks or STMs
  • 19. Datomic Pure functions -Datomic’s db as a value allows us to consider a function that queries the database as a pure function -db is a snapshot of the database at a certain point in time. -So, querying the same db instance will always produce the same result
  • 20. Impure functions Pure functions -functions that produce side effects should be marked as such. We use `!` at the end. -split code which handles and transforms data from code that handles side effects -should be moved to the borders of the flow, if possible -Consider returning a future/promise like value, so side effect results can be composed (e.g with manifold or finagle) https://github.com/ztellman/manifold https://github.com/twitter/finagle
  • 22. Schema Legacy Majority of our code base was written before clojure.spec existed, so I’ll be talking about the Schema library instead. Most principles apply to clojure.spec as well.
  • 23. Schema/Spec Documentation -Clojure doesn’t force you to write types -parameter names are not enough -declaring types helps a lot when glancing at the function -values can be verified against a schema
  • 24. Function declaration Schema/spec -All pure functions declare schemas for parameters and return value -All impure functions declare for parameters and don’t declare output type if it’s not relevant. -Validated at runtime in dev/test environments, on every function call -Validation is off on production.
  • 25. Wire formats Schema/Spec -Internal schemas are your domain models -Wire schemas are how you expose data to other services/ clients -If they are different, you can evolve internal schemas without breaking clients -Need an adapter layer -wire schemas are always validated on entry/exit points, specially in production -single repository for all wire schemas (for all 60+ services) -caveat: this repository has a really high churn. Beware
  • 26. Growing Schemas Spec-ulation Please watch Rich Hickey’s talk at Clojure Conj 2016 Spec-ulation: https://www.youtube.com/watch?v=oyLBGkS5ICk
  • 27. Ports and Adapters (a.k.a Hexagonal Architecture) SOUTHEAST BRAZIL REGION FROM SPACE
  • 28. Ports and Adapters Definition Core logic is independent to how we can call it (yellow) A port is an entry-point of the application (blue) An adapter is the bridge between a port and the core logic (red) http://www.dossier-andreas.net/software_architecture/ports_and_adapters.html http://alistair.cockburn.us/Hexagonal+architecture
  • 29. Ports and Adapters (Nubank version) Extended Definition Pure business logic (green) Controller logic wires the flow between the ports (yellow) A port is an entry-point of the application (blue) An adapter is the bridge between a port and the core logic (red)
  • 30. Ports (Components) Ports and Adapters -Ports are initialised at startup -Each port has a corresponding component -Serializes data to a transport format (e.g JSON, Transit) -Usually library code shared by all services -Tested via integration tests HTTP Kafka Datomic File Storage Metrics E-mail
  • 31. Adapters (Diplomat) Ports and Adapters -Adapters are the interface to ports -Contain HTTP and Kafka consumer handlers -Adapt wire schema to internal schema -Calls and is called by controller functions -Tested with fake versions of the port components, or mocks HTTP Kafka Datomic File Storage Metrics E-mail
  • 32. Controllers Ports and Adapters -Controllers wires the flow between entry-point and the side effects -Only deals with internal schemas -Delegates business logic to pure functions -Composes side effect results -Tested mostly with mocks HTTP Kafka Datomic File Storage Metrics E-mail
  • 33. Business Logic Ports and Adapters -Handles and transforms immutable data -Pure functions -Best place to enforce invariants and type checks (e.g using clojure.spec) -Can be tested using generative testing -Should be the largest part of the application HTTP Kafka Datomic File Storage Metrics E-mail
  • 34. Microservices Ports and Adapters -Each service follows about the same design -Services communicate with each other using one of the ports (e.g HTTP or Kafka) -Services DON’T share databases -HTTP responses contain hypermedia, so we can replace a service without having to change clients -Tested with end to end tests, with all services deployed
  • 35. Clojure is simple Keep your design simple Keep your architecture simple SÃO PAULO, BRASIL