0% found this document useful (0 votes)
30 views22 pages

Microservices Study Notes

The document provides comprehensive study notes on Microservices Architecture, covering its introduction, essentials, and design principles across three modules. It contrasts microservices with monolithic architecture, detailing the advantages and challenges of each, and outlines key principles, communication methods, and frameworks like Spring Boot. The notes emphasize the evolution of microservices, their characteristics, and the importance of independent deployments for modern application development.

Uploaded by

10a41om
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views22 pages

Microservices Study Notes

The document provides comprehensive study notes on Microservices Architecture, covering its introduction, essentials, and design principles across three modules. It contrasts microservices with monolithic architecture, detailing the advantages and challenges of each, and outlines key principles, communication methods, and frameworks like Spring Boot. The notes emphasize the evolution of microservices, their characteristics, and the importance of independent deployments for modern application development.

Uploaded by

10a41om
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Microservices Architecture — Complete Study Notes

MICROSERVICES ARCHITECTURE
Complete Study Notes

Modules 1, 2 & 3 | CO1 · CO2 · CO3

Module 1 Module 2 Module 3


Microservices: Introduction Units Microservices: Essentials Units Microservices: Design Units 3.1–
1.1 & 1.2 3 Hours | CO1 2.1–2.4 12 Hours | CO2 3.3 10 Hours | CO3

Topics Covered
Module 1 Module 2 Module 3
• Monolithic Architecture • • Monolithic App Challenges • • Microservices Design Patterns
History of Microservices • Early Microservices Principles • • Best Practices •
Adopters (Amazon, Netflix) • Characteristics & Polyglot • Communication Mechanisms •
Spring Framework & Spring Automation & Ecosystem • 12-Factor Methodology • Data
Boot • Spring Data JPA • Distributed Architecture • SOA Persistence Patterns • Domain-
Microservice Communication vs Microservices Driven Design (DDD)

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

MODULE 1
CO1 | 3 Hours
Microservices: Introduction

1.1 Introduction — Monolithic Architecture

What is a Monolithic Application?


A monolithic application is built as a single deployment unit — a single JAR/WAR file — that runs as
one process. All components (UI, business logic, data access) are tightly bundled together.

Characteristics of Monolithic Applications


• Single Codebase: All modules live in one repository (e.g., GitHub). UI, business logic, and data
layers are in one project.
• Tightly Coupled Components: Changing one part often affects others — high interdependency.
• Single Deployment Unit: Any update, even a one-line bug fix, requires redeploying the entire
application.
• Shared Database: All modules share a single centralized database.
• Easy to Test (initially): End-to-end tests are simple since all components run together.
• Less Network Overhead: All calls happen in-process — no inter-service network latency.

Advantages of Monolithic Architecture


• Simple development setup — one codebase, one IDE, one server.
• Easy to scale horizontally — run multiple instances behind a load balancer.
• Straightforward end-to-end testing with tools like Selenium.
• Best suited for small-to-medium applications with stable requirements.

Disadvantages of Monolithic Architecture


Disadvantage Explanation
Deployment Coupling Any small change requires full rebuild and redeployment — risky
and slow.
Single Point of Failure A bug in one module can crash the entire system.
Difficult Independent Scaling Cannot scale one module alone; entire app must be duplicated.
Technology Lock-In Entire app must use one language/framework — cannot mix tech
stacks.
Long Development Cycles Large codebase slows IDE, builds, and team coordination.
Slow Startup Times Large app size increases server and IDE startup times.
Reduced CI/CD Agility Tight coupling makes CI/CD pipelines difficult and deployment risky.
High Key-Person Dependency Only a few developers understand the entire codebase.

🔑 Key Insight

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

As a solution to monolithic limitations, Service Oriented Architecture (SOA) and Enterprise


Service Bus (ESB) emerged. These eventually evolved into Microservices architecture.

1.2 History of Microservices & Early Adopters

Evolution Timeline
Era Milestone
1990s Distributed computing concepts & CORBA (Common Object Request Broker
Architecture) laid early groundwork.
Early 2000s SOA gained prominence, influenced by IBM, Microsoft, and Oracle. No single creator
— it evolved as a paradigm.
~2010 Microservices began gaining traction as cloud computing and DevOps became
mainstream.
2014 Martin Fowler & James Lewis popularized the term 'Microservices' via their
ThoughtWorks article.

Early Adopters
• Amazon: Used microservices to solve massive scalability challenges in their e-commerce
platform.
• Netflix: Adopted microservices to address reliability and scalability in their streaming platform —
brought the concept into mainstream.

⭐ Important — Exam Note


Creator of Microservices: Martin Fowler & James Lewis (2014 — ThoughtWorks article)
Creator of SOA: No single creator — evolved in early 2000s (IBM, Microsoft, Oracle)
Early Adopters: Amazon and Netflix

Self-Study: Monolithic vs Microservices — Architecture


Comparison

What is Microservices Architecture?


Microservices is an architectural style in which a single application is composed of many small, loosely
coupled, and independently deployable services. Each service runs in its own process and
communicates via lightweight mechanisms such as HTTP/REST.

Martin Fowler's Definition (2014)


"The microservice architectural style is an approach to developing a single application as a suite
of small services, each running in its own process and communicating with lightweight
mechanisms, often an HTTP resource API. These services are built around business capabilities
and are independently deployable by fully automated deployment machinery."

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

Architecture Granularity Comparison


Architecture Granularity Key Characteristic
Monolithic Single Unit All layers tightly bundled in one deployable artifact.
SOA Coarse-grained Large services communicating via ESB (Enterprise
Service Bus).
Microservices Fine-grained Small, focused services with independent databases &
deployments.

Detailed Comparison: Monolithic vs Microservices


Feature Monolithic Microservices
Architecture Tightly coupled; single deployment Distributed & loosely coupled; each
unit. service independently deployable via
APIs.
Scalability Vertical Scaling — add more Horizontal Scaling — add more
CPU/RAM to one server. servers, distribute via load balancer.
Deployment Entire application deployed as one Individual services deployed
unit. independently.
Development One large codebase; coordination Independent teams work on separate
among large teams. services simultaneously.
Fault Isolation Failure in one module can crash the Failure in one service usually does
entire app. not impact others.
Technology Stack Single technology stack for all Each service can use a different stack
components. (polyglot).
Database Single shared database for all Each service has its own separate
modules. database.
Maintenance Harder as codebase grows. Easier — smaller, focused services.
Use Case Small-medium apps with simple Large, complex, evolving applications.
requirements.

Key Principles of Microservices Architecture


Principle Description Benefit
Single Responsibility Each service has one well-defined Promotes modularity; easier to
(SRP) responsibility. develop, maintain, and scale.
Loose Coupling Minimize dependencies between Services evolve independently;
services. reduces cascading failures.
Independent Each service is independently Faster/more frequent releases;
Deployments deployable. improved agility.
Business Capabilities Services aligned with business Better organizational alignment.
domains.
Decentralized No centralized control over Empowers teams to choose best
Governance technology choices. tech for their service.

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

API-First Approach Clear, well-documented APIs for each Enables seamless communication
service. and integration.
Data Ownership Each service owns its own data. Promotes data independence;
services can evolve
independently.
Fault Tolerance Design services to be resilient to System continues functioning
failures. even if individual services fail.
Observability Built-in monitoring and logging. Proactive issue identification;
improved stability.
Continuous Delivery Automate build, test, and deployment. Faster delivery cycles; reduced
manual effort.

Service-Oriented Architecture (SOA)


SOA is an architectural style that supports service-orientation — services are large, coarse-grained,
and communicate via a central Enterprise Service Bus (ESB).

SOA vs Microservices — Key Differences


Aspect SOA Microservices
Service Size Coarse-grained (e.g., one service for Fine-grained (e.g., separate services
all Order Management) for Order Creation, Tracking,
Payment)
Communication Central ESB (Enterprise Service Bus) Direct communication via REST,
HTTP, gRPC
Data Storage Services share the same database Each service has its own private
database
Coupling More dependent on other services Independent and loosely connected
Technology Single tech stack Mixed tech stack (polyglot)
Scalability Harder to scale parts separately Easy to scale individual services
Deployment Slower and centralized Faster and independent
Failures One failure can affect the whole Failures isolated to one service
system
Approach Share-as-much-as-possible Share-as-little-as-possible

Spring Framework, Spring Boot & Spring Data JPA

What is Spring Framework?


Spring is a lightweight, open-source Java framework based on Dependency Injection (DI) and Aspect-
Oriented Programming (AOP). It is loosely coupled and highly modular.

Spring IoC Container


In Spring, objects are created, wired together, and managed inside the Spring Container (IoC
Container). Two types:

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes


Dependency Injection (DI)


DI is a design pattern that removes hard-coded dependencies from code, making it easier to test and
maintain. Rather than creating objects internally, dependencies are injected from outside.

Types of Dependency Injection


Type How It Works Best For Notes
Constructor Dependency passed via Mandatory Promotes immutability
Injection constructor: dependencies — recommended
Employee(Address address) approach
Setter Injection Dependency set via setter Optional More flexible; allows
method after creation: dependencies changing dependencies
setAddress(Address)
Field Injection Dependency injected directly Quick prototype code NOT recommended —
into field using @Autowired hides dependencies,
harder to test

Inversion of Control (IoC)


IoC is a design principle where the program's control flow is managed by a framework/container instead
of the code itself. DI is a specific type of IoC.

Spring Boot
Spring Boot is a framework built on top of Spring Framework that simplifies development by providing
auto-configuration, embedded servers, and production-ready features. Ideal for microservices.

Key Features of Spring Boot


Feature Description
Auto-Configuration Automatically configures beans based on classpath dependencies
— reduces manual setup.
Embedded Server Comes with embedded Tomcat/Jetty/Undertow — run web apps
without external server setup.
Starter Dependencies Pre-built 'starter' packages simplify dependency management (e.g.,
spring-boot-starter-web).
Production-Ready Features Includes Spring Actuator for monitoring, health checks, and metrics.

@SpringBootApplication — Three Annotations in One


Annotation Purpose
@Configuration Marks the class as a configuration source (@Bean definitions).

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

@EnableAutoConfiguration Enables auto-configuration based on [Link] dependencies.


@ComponentScan Scans the package for @Component, @Service, @Repository,
@Controller and registers them as beans.

Spring Boot Request Flow


Request → Response Flow
1. Client (Browser, Mobile, Postman) sends HTTP request
2. Controller Layer (@RestController / @Controller) handles the request
3. Controller invokes Service Layer (business logic)
4. Service Layer interacts with Repository Layer (data access)
5. Repository Layer communicates with the Database
6. Response travels back: DB → Repository → Service → Controller → Client
7. Exception Handling Layer manages errors and sends proper error responses

Spring Data JPA


Component Description
Spring Data JPA Abstraction layer on top of JPA — provides repositories and derived query
methods. Reduces boilerplate.
JPA Java Persistence API — specification for object-relational mapping (ORM) in
Java.
Hibernate Most popular JPA implementation (Spring Boot default). Generates and
executes SQL via JDBC.
JDBC Low-level database connectivity layer.

Common JpaRepository Methods


Method Description
save(entity) Saves or updates an entity
findById(id) Retrieves an entity by its primary key
findAll() Retrieves all entities from the database
deleteById(id) Deletes an entity by its ID
count() Returns total number of entities
existsById(id) Checks if an entity with the given ID exists

Microservice Communication
Synchronous (Request/Response) Asynchronous (Message Passing)
Protocol: HTTP/REST, gRPC Protocol: RabbitMQ, Kafka, AWS SQS
Blocking — Service A waits for Service B's Non-blocking — Service A continues while B
response processes later

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

Use when: critical ops, immediate user Use when: background tasks, decoupling for
feedback scalability
Simpler to implement Requires additional message broker
infrastructure

HTTP Client Tools Comparison


Tool Type Use Case Status
RestTemplate Synchronous, Legacy systems / Simple apps Deprecated for
Blocking reactive use in
Spring Boot 2.4+
WebClient Reactive, Non- High-performance / Modern apps Recommended for
blocking modern
applications
OpenFeign Declarative Microservice-to-microservice Recommended for
communication microservices —
uses @FeignClient

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

MODULE 2
CO2 | 12 Hours
Microservices: Essentials

2.1 Monolithic Application Challenges

IT Industry Transformation — Four Key Aspects of Every Application


Aspect Traditional (Monolithic) Modern (Cloud Native)
Development Process Waterfall, slow release cycles Agile, DevOps, continuous delivery
Application Architecture Monolithic — single deployable unit Microservices — distributed
services
Deployment & Packaging JAR/WAR files on physical servers Containers (Docker), Kubernetes
Application Infrastructure On-premise physical servers Cloud environments (AWS, GCP,
Azure)

Monolithic Application Challenges — In Detail


Challenge Root Cause Impact
Deployment Coupling All components bundled A 1-line bug fix requires full rebuild and
together redeployment — risky.
Single Point of Failure No fault isolation between A crash in one module brings the entire
modules system down.
Wasteful Horizontal Cannot scale components Scaling the payment module means scaling
Scaling independently the ENTIRE app.
Technology Lock-In All components compiled Cannot use Python for one module and Java
together for another.
Slow Development Large, shared codebase Long build times, testing cycles, team conflicts.
Slow onboarding.
High Maintenance Cost Growing codebase Changes become increasingly risky and
complexity expensive over time.

🔑 Key Exam Point


Monolithic architecture follows a 'deploy everything or nothing' principle — this is the ROOT
CAUSE of most of its challenges. Microservices solve this by allowing independent deployments.

2.2 Microservices Principles, Characteristics & Polyglot


Architecture

What is Microservices Architecture?

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

Microservices is an architectural style that structures an application as a set of loosely coupled


services organized around business capabilities. Each service is autonomous, self-contained, and
independently deployable.

The Two Foundational Principles


Core Principles
1. Single Responsibility Per Microservice — Each service does ONE thing and does it well. It
owns a single, well-defined business capability.
2. Microservices are Autonomous — Each service is self-contained and independently
deployable. It takes FULL responsibility for a business capability — including its own data and
logic.

Characteristics of Microservices
Characteristic Explanation
Service Contract Each microservice exposes a well-defined API/interface (contract). Clients
depend on this contract, not on internal implementation.
Loose Coupling Microservices are minimally dependent on each other. A change in one
service should not require changes in others.
Service Abstraction Internal implementation details are hidden from consumers. Only the
interface (contract) is visible.
Service Reuse Microservices can be reused across multiple applications since they expose
standard interfaces.
Statelessness No client session state is maintained between requests. Each request is
self-contained. State is stored externally (databases, Redis).
Service Interoperability Services communicate regardless of tech stack, using standard protocols
like HTTP/REST.
Service Composability Services can be combined (composed) to build complex business workflows
via orchestration or choreography.

Service Composability: Orchestration vs Choreography


Service Orchestration Service Choreography
A central controller actively manages all No central controller — each service knows
elements and interactions. what to do and when.
Like a conductor directing musicians in an Like dancers following the music without a
orchestra. choreographer directing them.
One service directs the others. Services react to events independently.

Polyglot Architecture
Polyglot = 'many languages'. One of the most powerful features of microservices — each service can
be built with different technologies:
• Different programming languages: Java, Python, [Link], Go, C#, etc.
• Different frameworks: Spring Boot, Flask, Express, Quarkus, etc.

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

• Different databases: MySQL, MongoDB, Redis, Cassandra, PostgreSQL, etc.


• Different deployment mechanisms: Docker containers, serverless functions, etc.

Why Polyglot Works


Services communicate through standard APIs (REST/HTTP, gRPC, messaging) — NOT shared
code or memory. This is why polyglot architecture is ONLY possible in microservices. In a
monolith, the entire application is locked to one language/framework.

2.3 Automation in Microservices Environment & Supporting


Ecosystem

Why Automation is Essential


Unlike a monolithic application (one deployable unit), a microservices system can consist of dozens or
hundreds of individual services. Managing these manually is practically impossible.

What Gets Automated?


Automation Area What It Does Tools / Examples
Automated Builds Code is automatically compiled and Jenkins, GitHub Actions, GitLab CI
built on every commit.
Automated Testing Unit, integration, and contract tests JUnit, Mockito, Postman,
run automatically. TestContainers
Automated Deployment Services are automatically deployed Kubernetes, Helm, ArgoCD
to staging/production.
Elastic Scaling Services automatically scale up/down Kubernetes HPA, AWS Auto
based on demand. Scaling
Infrastructure as Code Infrastructure provisioned Terraform, Ansible,
automatically via code. CloudFormation
Service Mesh Automates service-to-service Istio, Linkerd, Consul Connect
communication, security,
observability.

Supporting Ecosystem Components


Component Purpose / Role Examples
API Gateway / Service Single entry point for all client requests. Kong, NGINX, Spring
Routing Handles routing, authentication, rate limiting, Cloud Gateway, AWS API
load balancing, SSL. Gateway
Service Registry Directory of all available microservices and Eureka, Consul, Zookeeper
their locations. Services register & discover
each other dynamically.
Service Logging & Centralizes log collection. Provides real-time ELK Stack (Elasticsearch,
Monitoring monitoring, alerting, and dashboards. Logstash, Kibana),
Prometheus, Grafana

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

DevOps Processes Combines dev and ops teams to automate Jenkins, GitHub Actions,
CI/CD pipelines for rapid, reliable delivery. GitLab CI/CD
Self-Managed Cloud Env Cloud infrastructure automatically detects Kubernetes health checks
failures, restarts services, redistributes load. and auto-restart

Containerization
Containerization is a form of virtualization where applications run in isolated user spaces (containers),
sharing the same OS kernel.
• Everything an app needs is encapsulated: binaries, libraries, config files, and dependencies.

2.4 Microservices & Distributed Architecture, Related Architecture


Styles

Microservices as a Distributed System


Each microservice encapsulates its own logic and data within a service boundary. This creates two key
characteristics:

Early Adopters of Microservices


Company Reason for Adoption
Netflix Migrated from monolith to cloud-based microservices ~10 years ago to
solve reliability and scalability issues.
Amazon Decomposed large e-commerce platform into hundreds of microservices for
scalability.
Uber Real-time ride-sharing with complex distributed microservices.
Airbnb Marketplace services broken into independent deployable units.
eBay Auction and marketplace platform migration.
Twitter/X, PayPal, All adopted microservices for scale and agility.
Nordstrom

SOA vs Microservices — Detailed Comparison


Comparison Point SOA Microservices (MSA)
Architecture Approach Share-as-much-as-possible Share-as-little-as-possible
Focus Business functionality reuse Bounded context — each service
owns its domain
Governance Common governance and Distributed governance — each
standards team decides independently

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

Communication Enterprise Service Bus (ESB) — Simple messaging — lightweight,


heavyweight no central ESB
Protocols Multiple (SOAP, REST, etc.) Lightweight protocols (HTTP/REST)
Databases Traditional Relational DBs Modern Relational + NoSQL
DevOps Focus Becoming popular Strong DevOps focus from the start
Migration/Change Modify the monolith for systematic Create a new service for systematic
change change

Related Architecture Styles


Style Key Concept
Twelve-Factor Apps Set of 12 principles for cloud-native, SaaS applications. Covered in depth
in Module 3.
Serverless Computing Code runs in stateless functions triggered by events — infrastructure fully
managed by cloud provider.
Lambda Architecture Big data processing pattern combining batch and stream processing.
DevOps Culture combining development and operations for rapid, reliable delivery
via CI/CD.
Containers/Docker Packaged apps in isolated containers — the de facto standard for
deploying microservices.
Reactive Microservices Event-driven, non-blocking services using reactive programming
(WebFlux, Vert.x).

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

MODULE 3
CO3 | 10 Hours
Microservices: Design

3.1 Architecture of a Multi-Microservice Application

Three Fundamental Layers


Layer Role Details
API Layer Entry point for all client Enables inter-service communication over HTTP,
requests gRPC, TCP/UDP. Clients connect via API Gateway or
directly.
Logic Layer Implements actual Focused on a SINGLE business task. Can be written in
business logic any language (Java, Python, Go — polyglot).
Data Store Layer Provides persistence Databases, log files, file storage. Each microservice
ideally owns its own private data store.

Key Design Insight


Each microservice is independently deployable, independently scalable, and uses its own private
database. The polyglot nature means different languages and databases can coexist across
services.

3.2 Best Practices for Designing Microservices

Core Design Principle: Single Responsibility


Each microservice must implement ONLY a single piece of the application's functionality. Avoid 'god
services' that handle too many concerns — this recreates the monolith problem.

Five Key Design Requirements


Requirement Description Key Points
1. Responsive Microservices must return a response to Implement proper fallback
clients even when the service fails. mechanisms. Never hang or timeout
silently.
2. Backward API changes must NOT break existing Use API versioning (/v1/, /v2/). Never
Compatible clients. remove/rename fields without
deprecation notices.
3. Flexible Each service can specify its HTTP/REST, gRPC, AMQP,
Communication communication protocol. TCP/UDP — choose per service
needs.
4. Idempotent Calling a service multiple times with the Critical for handling network retries.
same request must produce the SAME Ensures consistency, safe error
outcome. handling, and fault tolerance.

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

5. Efficient Design for easy monitoring and Use a centralized log system. Emit
Operation troubleshooting. structured logs that can be
aggregated and analyzed.

Idempotent vs Safe — Critical Distinction


Idempotent vs Safe
Safe method: Does NOT change state — it only reads, never writes. Example: x + 0
Idempotent method: Produces the same result every time, but MAY modify state. Example: x = 5
(always results in x being 5, but changes state if x was different before)
RULE: ALL safe methods are idempotent, but NOT all idempotent methods are safe.

3.3 Communication Mechanisms in Microservices

Communication Protocols Overview


Protocol Type Use Case
HTTP/REST Synchronous, request- Most common — CRUD operations via GET,
response POST, PUT, DELETE
gRPC Synchronous, high- High-performance inter-service
performance RPC communication, streaming
AMQP (RabbitMQ) Asynchronous messaging Message queues for event-driven patterns
Apache Kafka Asynchronous streaming Event streams, high-throughput data
pipelines

API Gateway Pattern


An API Gateway is a single-entry point for ALL requests to backend microservices. It acts as the 'front
door' of the microservices ecosystem.

Benefits of API Gateway


Benefit Description
Client Insulation Clients don't need to know which service handles which function or where
services are located.
Request Aggregation Gateway can aggregate data from multiple services in a single client
round-trip — reduces mobile overhead.
Protocol Translation Translates public-facing protocols to whatever internal protocols the
services use.
Simplified Client Code Multi-service orchestration logic moves from client into the gateway.
Authentication Handling Gateway authenticates users and passes access tokens to backend
services.
Circuit Breaker Handles service failures gracefully using circuit breaker patterns.

Backend for Frontend (BFF) Pattern


Modules 1, 2 & 3 | CO1 · CO2 · CO3
Microservices Architecture — Complete Study Notes

A variant of the API Gateway pattern — instead of one shared gateway, a separate gateway is defined
for each client type: one for mobile, one for web, one for third-party integrations. This gives each client
type an optimized API.

Drawbacks of API Gateway


• Increased complexity — another component to develop, deploy, and manage.
• Increased response time — an additional network hop through the gateway (usually
insignificant).

Asynchronous Communication — Best Practice


Best Practice: Prefer Async Communication
Minimizing direct synchronous communication between microservices is a key design principle.
Async advantages: calling service can continue without waiting — services are more decoupled,
independently scalable, and more resilient to partial failures.
Tools: Message Queues (RabbitMQ, Kafka) for event-driven patterns; Streaming Systems
(Kafka, AWS Kinesis) for event streams.

3.4 The 12-Factor Methodology


The 12-Factor Methodology is a set of rules and guidelines for developing Software as a Service
(SaaS) and cloud-native applications. Microservices should ideally adhere to all 12 factors.

# Factor Category One-Line Summary


1 Codebase Code One codebase per service, tracked in version control
2 Dependencies Code Explicitly declare and isolate all dependencies
3 Config Code Store config in the environment, not in code
4 Backing Services Dependencies Treat external services as attached, swappable resources
5 Build, Release, Code Strictly separate build, release, and run stages
Run
6 Processes Dependencies Stateless processes; store state in external data store
7 Port Binding Dependencies Export services via port numbers, not domain names
8 Concurrency Dependencies Scale out by adding process instances
9 Disposability Operate Fast startup, graceful shutdown
10 Dev/Prod Parity Code Keep all environments as similar as possible
11 Logs Operate Treat logs as event streams; don't manage log files
12 Admin Processes Operate Run admin tasks as one-off processes in same
environment

Factor 1: Codebase
One codebase per microservice tracked in version control (Git), many deploys.

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

Every microservice needs its OWN dedicated codebase in version control.


Microservices must NOT share codebases with other microservices.
The same codebase can be deployed to multiple environments (dev, staging, production).
All assets — source code, provisioning scripts, config — stored in the repo.

Factor 2: Dependencies
Explicitly declare and isolate all dependencies using a manifest file.
Only code unique to the service is stored in source control.
External artifacts (JARs, NPM packages, Python packages) referenced in a dependency
manifest.
Tools: Maven/Gradle (Java), npm/[Link] ([Link]), pip/[Link] (Python).
Dependencies are loaded from the manifest at runtime — NOT stored with source code.

Factor 3: Config
Store configuration in the environment — NOT hardcoded in the application.
Config (credentials, connection strings, ports) may differ between deployments.
Inject config via environment variables — never hardcode in application code.
Build the application ONCE; apply different configuration at runtime per environment.
Tools: Java .properties files, Kubernetes ConfigMaps, Docker Compose environment variables.

Factor 4: Backing Services


Treat ALL external services (databases, queues, email) as attached, swappable
resources.
Backing services include databases, message queues, email servers, third-party APIs.
Do NOT distinguish between local and third-party services — all accessed via URL/API.
Decouple backing services so they can be swapped without code changes.
Benefit: switching from PostgreSQL to MySQL requires NO codebase change.

Factor 5: Build, Release, Run


Strictly separate the three stages of the deployment pipeline.
Build Stage: Code retrieved and compiled into an executable artifact (Docker image, JAR).
Release Stage: Build artifact combined with environment-specific config to create a deployable
release.
Run Stage: Runtime environment provisioned and application deployed.
Build ONCE — then test, promote, and deploy the same image across all environments.

Factor 6: Processes

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

Execute the app as stateless processes — store state externally.


Microservices are STATELESS — no process tracks the state of another.
No session data or workflow state stored in process memory.
State that needs to persist is stored in external cache (Redis) or database.
Stateless processes can be added or removed at will to address load bursts.

Factor 7: Port Binding


A microservice is identifiable on the network by its PORT NUMBER — not a domain
name.
Domain names and IP addresses can be reassigned dynamically — unreliable as identifiers.
Port numbers are more stable and manageable reference points.
Common ports: 80 (HTTP), 443 (HTTPS), 3306 (MySQL), 27017 (MongoDB), 22 (SSH).
Port collisions resolved using port forwarding.

Factor 8: Concurrency
Scale out via the process model — organize processes by type and scale each
independently.
When web server load increases, scale ONLY the web server tier.
When business logic is the bottleneck, scale ONLY that tier.
Without this, you must scale the entire application — expensive and wasteful.
Container orchestration (Kubernetes) automates this horizontal scaling.

Factor 9: Disposability
Maximize robustness with fast startup and graceful shutdown.
Fast startup: All DB connections and config must be ready before the service serves traffic.
Graceful shutdown: Complete in-flight requests, terminate DB connections, log all shutdown
activity.
Supports rolling deployments, auto-scaling, and fault recovery.
Microservice processes can be started or stopped at any time.

Factor 10: Dev/Prod Parity


Keep development, staging, and production environments as similar as possible.
Use the same tools, libraries, and configurations across all environments.
Use containers (Docker) to ensure environment consistency.
Minimizes 'it works on my machine' problems.
NEVER deploy directly from dev to prod — always go through staging.

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

Factor 11: Logs


Treat logs as event streams — write to stdout; never manage log files.
A microservice writes logs to its event stream — time-ordered, unbuffered output to stdout/stderr.
The microservice must NEVER handle routing or storage of its own log stream.
Different consumers can subscribe: error monitoring, audit, archive.
Even if the microservice crashes, log data lives on in the stream/store.

Factor 12: Admin Processes


Run admin/management tasks as one-off processes in the same environment.
Maintenance tasks (DB migrations, cache clearing, data cleanup) run as one-off processes.
These must run in an IDENTICAL environment to the regular application microservices.
Example: running a database migration script in the same Docker container as the application.

3.5 Data Persistence Patterns for Microservices


The core principle: private persistent data should be accessible ONLY through the owning
microservice's API — never directly by other services.

Three Variants of Data Isolation


Variant Description Isolation Level
Private Tables Each microservice owns a dedicated set of Low — still on shared DB
tables within a shared database. server.
Private Schema Each microservice owns a private database Medium — schema-level
schema within a shared DB server. separation.
Private Database Server Each microservice owns a completely High — strongest isolation
separate database server. (recommended).

The Anti-Pattern: Shared Database Schema


⚠ Anti-Pattern: Shared Schema
Advantage: Simple — only one database to manage.
Disadvantage 1: Microservices interfere with each other when accessing the same tables.
Disadvantage 2: Development slows — teams must coordinate all schema changes.
Disadvantage 3: Increases inter-service dependencies, defeating a key microservices benefit.
Verdict: Tempting for small teams but becomes a serious bottleneck as services grow. Always
prefer private databases from the start.

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

Oracle Multi-Tenant Architecture


• Oracle enables a database to function as a multi-tenant Container Database (CDB).
• A CDB can include many Pluggable Databases (PDBs) — each PDB appears as a standalone
database to clients.
• Best choice for microservices: PDBs provide bounded context isolation, data security, and high
availability per service.

3.6 Domain-Driven Design (DDD) for Microservices

What is DDD?
Domain-Driven Design (DDD) is a software design philosophy coined by Eric Evans in his book
'Domain-Driven Design: Tackling Complexity in the Heart of Software'. DDD bridges design and
development by creating highly expressive models that everyone — developers AND domain experts
— can understand.

Three Core Principles of DDD


1. Focus on the core domain and domain logic.
2. Base complex designs on models of the domain.
3. Constantly collaborate with domain experts to improve the application model and resolve
domain issues.

Key DDD Terminology


Term Definition
Domain The subject area to which the user applies the software. Related to the
BUSINESS, not the technology.
Context The setting in which a word or statement appears that determines its
meaning. Statements can only be understood in context.
Model A system of abstractions that describes selected aspects of a domain and
can be used to solve problems.
Ubiquitous Language A language structured around the domain model, used by ALL team
members — developers AND domain experts — to connect team activities
with the software.
Bounded Context A boundary (typically a subsystem) within which a particular model is
defined and applicable. In microservices, each service typically maps to a
bounded context.

DDD Building Blocks


Building Block Definition Example
Entity Object identified by its continuous identity, Customer (identified by
not just its attribute values. CustomerID — same customer
even if name/address changes)

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

Value Object Immutable object with attributes but NO Money (amount=100,


distinct identity. Two value objects with currency=USD) — any two with
same attributes are equal. same values are interchangeable
Domain Event Records a discrete event related to model OrderPlaced, PaymentProcessed,
activity. Only events domain experts care ItemShipped
about are modeled.
Aggregate Cluster of entities and value objects with Order aggregate containing
defined boundaries. External access only OrderLines, ShippingAddress,
through the aggregate root. PaymentMethod
Service Operation or business logic that doesn't TaxCalculationService —
naturally fit within an entity or value object. calculates taxes based on
multiple entities
Repository Provides a global interface to access all OrderRepository with CRUD
entities and value objects within an methods for Order aggregates
aggregate. Abstracts the data store.
Factory Encapsulates logic for creating complex OrderFactory — enforces all
objects. Clients use factory without business rules for valid order
needing construction logic. creation

DDD → Microservices Mapping


Bounded Context → maps 1:1 to a Microservice
Aggregate → has its own Repository
Domain Events → drive inter-service communication
Ubiquitous Language → shared vocabulary across dev team and domain experts

DDD Benefits & Challenges


Benefits Challenges
Eases Communication — ubiquitous language Requires Robust Domain Expertise — needs at
reduces misunderstandings between technical least one deep domain expert on the team.
and non-technical members.
Improves Flexibility — OO-based analysis Encourages Iterative Practices — DDD relies
makes the domain model modular and on constant iteration. Organizations used to
encapsulated — easy to change. waterfall may struggle.
Emphasizes Domain Over Interface — High upfront investment in modeling before
produces apps that accurately represent the significant code is written.
business domain.

QUICK REVISION SUMMARY

Topic Key Points to Remember


Monolithic Single JAR, tightly coupled, single DB. 'Deploy everything or nothing.'
Single point of failure.

Modules 1, 2 & 3 | CO1 · CO2 · CO3


Microservices Architecture — Complete Study Notes

SOA Coarse-grained services, communicate via ESB, shared DB, share-as-


much-as-possible approach.
Microservices Fine-grained, own DB, communicate via REST/HTTP/gRPC,
independently deployable, polyglot.
Spring Framework Lightweight, open-source, based on DI and AOP. Creator: Rod Johnson
(2002).
Spring Boot Built on Spring — auto-config, embedded server, starter dependencies.
Ideal for microservices.
Spring Data JPA Simplifies DB access using JPA. Built-in CRUD via JpaRepository. Uses
Hibernate by default.
Microservices Principles Single Responsibility + Autonomous = the two foundational principles.
Characteristics Service Contract, Loose Coupling, Abstraction, Reuse, Stateless,
Interoperability, Composability.
Polyglot Different language/DB per service — possible because services
communicate via standard APIs.
Automation CI/CD, containers (Docker), orchestration (Kubernetes), IaC (Terraform),
service mesh (Istio).
Ecosystem API Gateway, Service Registry, Logging & Monitoring, DevOps, Self-
healing Cloud Environment.
SOA vs MSA SOA: ESB, coarse-grained, shared governance. MSA: REST, fine-
grained, distributed governance.
12-Factor App 12 principles grouped in Code/Dependencies/Operate. Core theme: build
once, deploy everywhere, stateless, externalize config, stream logs.
Communication Sync: HTTP/REST, gRPC (blocking). Async: RabbitMQ, Kafka (non-
blocking). Prefer async to minimize coupling.
API Gateway Single entry point, handles routing, auth, circuit breaking, API
composition. BFF = one gateway per client type.
Data Persistence Private DB per service preferred. Anti-pattern: shared schema. Three
variants: Private Tables → Private Schema → Private DB Server.
DDD Bounded Context = one microservice. Building blocks: Entity, Value
Object, Domain Event, Aggregate, Service, Repository, Factory.
Creator of Microservices Martin Fowler & James Lewis — 2014 ThoughtWorks article.
Early Adopters Netflix (first major adopter), Amazon, Uber, Airbnb, eBay, Twitter, PayPal.

End of Notes — Microservices Architecture (Modules 1, 2 & 3)

Modules 1, 2 & 3 | CO1 · CO2 · CO3

You might also like