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

Software Engineering Culture - Improve Code Quality
Software Engineering Culture - Improve Code QualitySoftware Engineering Culture - Improve Code Quality
Software Engineering Culture - Improve Code QualityDmytro Patserkovskyi
 
[164] pinpoint
[164] pinpoint[164] pinpoint
[164] pinpointNAVER D2
 
Prometheus Overview
Prometheus OverviewPrometheus Overview
Prometheus OverviewBrian Brazil
 
Embarking on MuleSoft Automation Journey via RPA, Composer and Flex Gateway
Embarking on MuleSoft Automation Journey via RPA, Composer and Flex GatewayEmbarking on MuleSoft Automation Journey via RPA, Composer and Flex Gateway
Embarking on MuleSoft Automation Journey via RPA, Composer and Flex GatewayEva Mave Ng
 
Monitoring, Logging and Tracing on Kubernetes
Monitoring, Logging and Tracing on KubernetesMonitoring, Logging and Tracing on Kubernetes
Monitoring, Logging and Tracing on KubernetesMartin Etmajer
 
Automated Governance
Automated GovernanceAutomated Governance
Automated GovernanceJohn Willis
 
Intro to open source observability with grafana, prometheus, loki, and tempo(...
Intro to open source observability with grafana, prometheus, loki, and tempo(...Intro to open source observability with grafana, prometheus, loki, and tempo(...
Intro to open source observability with grafana, prometheus, loki, and tempo(...LibbySchulze
 
Confluent Enterprise Datasheet
Confluent Enterprise DatasheetConfluent Enterprise Datasheet
Confluent Enterprise Datasheetconfluent
 
Metrics Are Not Enough: Monitoring Apache Kafka and Streaming Applications
Metrics Are Not Enough: Monitoring Apache Kafka and Streaming ApplicationsMetrics Are Not Enough: Monitoring Apache Kafka and Streaming Applications
Metrics Are Not Enough: Monitoring Apache Kafka and Streaming Applicationsconfluent
 
Building APIs with the OpenApi Spec
Building APIs with the OpenApi SpecBuilding APIs with the OpenApi Spec
Building APIs with the OpenApi SpecPedro J. Molina
 
Build an Event-driven Microservices with Apache Kafka & Apache Flink with Ali...
Build an Event-driven Microservices with Apache Kafka & Apache Flink with Ali...Build an Event-driven Microservices with Apache Kafka & Apache Flink with Ali...
Build an Event-driven Microservices with Apache Kafka & Apache Flink with Ali...HostedbyConfluent
 
Grafana optimization for Prometheus
Grafana optimization for PrometheusGrafana optimization for Prometheus
Grafana optimization for PrometheusMitsuhiro Tanda
 
Integration Patterns for Microservices Architectures
Integration Patterns for Microservices ArchitecturesIntegration Patterns for Microservices Architectures
Integration Patterns for Microservices ArchitecturesNATS
 
Real time stock processing with apache nifi, apache flink and apache kafka
Real time stock processing with apache nifi, apache flink and apache kafkaReal time stock processing with apache nifi, apache flink and apache kafka
Real time stock processing with apache nifi, apache flink and apache kafkaTimothy Spann
 
Airflow at lyft for Airflow summit 2020 conference
Airflow at lyft for Airflow summit 2020 conferenceAirflow at lyft for Airflow summit 2020 conference
Airflow at lyft for Airflow summit 2020 conferenceTao Feng
 
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...Yevgeniy Brikman
 
Apache Kafka® and API Management
Apache Kafka® and API ManagementApache Kafka® and API Management
Apache Kafka® and API Managementconfluent
 
API Design and WebSocket
API Design and WebSocketAPI Design and WebSocket
API Design and WebSocketFrank Greco
 

What's hot (20)

Software Engineering Culture - Improve Code Quality
Software Engineering Culture - Improve Code QualitySoftware Engineering Culture - Improve Code Quality
Software Engineering Culture - Improve Code Quality
 
[164] pinpoint
[164] pinpoint[164] pinpoint
[164] pinpoint
 
Prometheus Overview
Prometheus OverviewPrometheus Overview
Prometheus Overview
 
Embarking on MuleSoft Automation Journey via RPA, Composer and Flex Gateway
Embarking on MuleSoft Automation Journey via RPA, Composer and Flex GatewayEmbarking on MuleSoft Automation Journey via RPA, Composer and Flex Gateway
Embarking on MuleSoft Automation Journey via RPA, Composer and Flex Gateway
 
Monitoring, Logging and Tracing on Kubernetes
Monitoring, Logging and Tracing on KubernetesMonitoring, Logging and Tracing on Kubernetes
Monitoring, Logging and Tracing on Kubernetes
 
Automated Governance
Automated GovernanceAutomated Governance
Automated Governance
 
Intro to open source observability with grafana, prometheus, loki, and tempo(...
Intro to open source observability with grafana, prometheus, loki, and tempo(...Intro to open source observability with grafana, prometheus, loki, and tempo(...
Intro to open source observability with grafana, prometheus, loki, and tempo(...
 
Confluent Enterprise Datasheet
Confluent Enterprise DatasheetConfluent Enterprise Datasheet
Confluent Enterprise Datasheet
 
Effective API Design
Effective API DesignEffective API Design
Effective API Design
 
Metrics Are Not Enough: Monitoring Apache Kafka and Streaming Applications
Metrics Are Not Enough: Monitoring Apache Kafka and Streaming ApplicationsMetrics Are Not Enough: Monitoring Apache Kafka and Streaming Applications
Metrics Are Not Enough: Monitoring Apache Kafka and Streaming Applications
 
Building APIs with the OpenApi Spec
Building APIs with the OpenApi SpecBuilding APIs with the OpenApi Spec
Building APIs with the OpenApi Spec
 
Build an Event-driven Microservices with Apache Kafka & Apache Flink with Ali...
Build an Event-driven Microservices with Apache Kafka & Apache Flink with Ali...Build an Event-driven Microservices with Apache Kafka & Apache Flink with Ali...
Build an Event-driven Microservices with Apache Kafka & Apache Flink with Ali...
 
Grafana optimization for Prometheus
Grafana optimization for PrometheusGrafana optimization for Prometheus
Grafana optimization for Prometheus
 
Container Patterns
Container PatternsContainer Patterns
Container Patterns
 
Integration Patterns for Microservices Architectures
Integration Patterns for Microservices ArchitecturesIntegration Patterns for Microservices Architectures
Integration Patterns for Microservices Architectures
 
Real time stock processing with apache nifi, apache flink and apache kafka
Real time stock processing with apache nifi, apache flink and apache kafkaReal time stock processing with apache nifi, apache flink and apache kafka
Real time stock processing with apache nifi, apache flink and apache kafka
 
Airflow at lyft for Airflow summit 2020 conference
Airflow at lyft for Airflow summit 2020 conferenceAirflow at lyft for Airflow summit 2020 conference
Airflow at lyft for Airflow summit 2020 conference
 
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...How to test infrastructure code: automated testing for Terraform, Kubernetes,...
How to test infrastructure code: automated testing for Terraform, Kubernetes,...
 
Apache Kafka® and API Management
Apache Kafka® and API ManagementApache Kafka® and API Management
Apache Kafka® and API Management
 
API Design and WebSocket
API Design and WebSocketAPI Design and WebSocket
API Design and WebSocket
 

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...
 

More from Lucas Cavalcanti dos Santos

Arquitetando uma instituição financeira moderna
Arquitetando uma instituição financeira modernaArquitetando uma instituição financeira moderna
Arquitetando uma instituição financeira modernaLucas Cavalcanti dos Santos
 
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
 
Building a powerful double entry accounting system
Building a powerful double entry accounting systemBuilding a powerful double entry accounting system
Building a powerful double entry accounting systemLucas Cavalcanti dos Santos
 
Testando a integracao entre serviços - Agile Brazil 2014
Testando a integracao entre serviços - Agile Brazil 2014Testando a integracao entre serviços - Agile Brazil 2014
Testando a integracao entre serviços - Agile Brazil 2014Lucas Cavalcanti dos Santos
 
O poder da linguagem Ruby e as suas consequências
O poder da linguagem Ruby e as suas consequênciasO poder da linguagem Ruby e as suas consequências
O poder da linguagem Ruby e as suas consequênciasLucas Cavalcanti dos Santos
 

More from Lucas Cavalcanti dos Santos (6)

Arquitetando uma instituição financeira moderna
Arquitetando uma instituição financeira modernaArquitetando uma instituição financeira moderna
Arquitetando uma instituição financeira moderna
 
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
 
Building a powerful double entry accounting system
Building a powerful double entry accounting systemBuilding a powerful double entry accounting system
Building a powerful double entry accounting system
 
Testando a integracao entre serviços - Agile Brazil 2014
Testando a integracao entre serviços - Agile Brazil 2014Testando a integracao entre serviços - Agile Brazil 2014
Testando a integracao entre serviços - Agile Brazil 2014
 
O poder da linguagem Ruby e as suas consequências
O poder da linguagem Ruby e as suas consequênciasO poder da linguagem Ruby e as suas consequências
O poder da linguagem Ruby e as suas consequências
 
Otimizacao prematura-agile-brazil-12
Otimizacao prematura-agile-brazil-12Otimizacao prematura-agile-brazil-12
Otimizacao prematura-agile-brazil-12
 

Recently uploaded

KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
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
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
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
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
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
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 

Recently uploaded (20)

KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
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
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
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
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 

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