Java & Spring Boot – Design Principles, Design Patterns & Microservices

Consolidated reference guide based on the supplied attachments • Suitable for KT, project reference and interview preparation

1. How These Concepts Fit Together

Design principles guide how code should be structured. Design patterns provide reusable solutions to common design problems. Microservices patterns address distributed-system concerns such as service communication, data ownership, resilience and consistency. The 12-Factor principles help make applications cloud/container friendly.
Code Level
SOLID, DRY, high cohesion, low coupling, DI/IoC.
Object Level
Creational, Structural and Behavioral GoF patterns.
Service Level
API Gateway, BFF, Saga, Circuit Breaker, Bulkhead, Retry.
Platform Level
Configuration, observability, containers, CI/CD and 12-Factor practices.

2. Design Patterns at a Glance

PatternTypeSpring Boot UsageTypical Example / Purpose
SingletonCreational@Component, @Service, @RepositorySpring beans are singleton-scoped by default: one bean instance per application context.
Factory MethodCreationalApplicationContext, BeanFactory, @BeanCreate objects dynamically while hiding creation logic.
BuilderCreationalDTOs, response objects, Lombok @BuilderUserResponse.builder().id(1).name("John").build()
PrototypeCreational@Scope("prototype")A new bean instance is created whenever it is requested from the container.
AdapterStructuralSpring Security, legacy/external integrationsConvert an external API/model into an internal domain model.
DecoratorStructuralLogging, validation, wrappers, servlet filtersAdd behavior without modifying the original object.
ProxyStructural@Transactional, @Cacheable, Spring AOPSpring creates proxies to apply transactions, caching, security and other cross-cutting behavior.
FacadeStructuralService layer, API gatewayExpose a simple interface over multiple backend services.
Template MethodBehavioralJdbcTemplate, RestTemplate, transaction templatesDefine a common workflow while allowing specific steps to vary.
StrategyBehavioralPayment, authentication, notification servicesSelect an algorithm/implementation dynamically at runtime.
ObserverBehavioralApplicationEventPublisher, @EventListenerPublish an event and notify independent subscribers.
CommandBehavioralCQRS, background jobs, task queuesEncapsulate an action/request as an object.
Chain of ResponsibilityBehavioralServlet filters, Spring Security filter chainPass a request through multiple processing steps.
IteratorBehavioralJava Collections, Streams, JPA pagingTraverse a collection sequentially without exposing its internal representation.
InterpreterBehavioralExpression/rule engines, DSL parsingInterpret expressions or business rules dynamically.

2.1 Creational Patterns – Simple Understanding

Singleton

“Give me the same managed instance.” Useful for stateless Spring services and shared infrastructure components.

Factory

“Decide which object to create.” Useful when the concrete implementation depends on type, configuration or runtime input.

Builder

“Build a complex object step by step.” Especially useful for immutable DTOs with many optional fields.

Prototype

“Give me a fresh instance.” Spring supports this with @Scope("prototype").

2.2 Structural Patterns

Structural patterns explain how objects/classes are composed to form larger structures while keeping dependencies manageable.

  • Adapter: useful at integration boundaries.
  • Decorator: adds responsibilities dynamically.
  • Proxy: controls access or adds cross-cutting behavior.
  • Facade: hides complexity behind a simple service/API.

2.3 Behavioral Patterns

Behavioral patterns focus on communication, responsibility and algorithms.

  • Strategy: interchangeable algorithms.
  • Observer: event notification.
  • Command: represents an operation as an object/message.
  • Chain of Responsibility: sequential processing/filtering.
  • Template Method: common workflow with variable steps.
  • Iterator: sequential traversal.
  • Interpreter: dynamic expression interpretation.

3. Microservices Design Patterns – Complete Overview

CategoryPatternDescriptionTypical Spring / Platform Implementation
DecompositionBusiness CapabilitySplit services by business domain/capability.Separate services such as order-service and user-service.
Subdomain / Bounded ContextDefine clear DDD business boundaries.Inventory, Catalog, Payment and Shipping contexts.
IntegrationAPI GatewaySingle entry point for clients.Spring Cloud Gateway.
AggregatorCombine multiple service responses.Composite REST service or gateway aggregation.
BFFSeparate API optimized for each client type.Web BFF and Mobile BFF.
DatabaseDatabase per ServiceEach service owns its data.Spring Data JPA with separate database/schema.
Shared DatabaseMultiple services share a schema; generally increases coupling.Legacy-system or migration scenarios.
ReliabilityCircuit BreakerPrevent cascading failures.Resilience4j CircuitBreaker.
RetryRetry transient failures carefully.Resilience4j Retry / Spring Retry.
TimeoutLimit remote-call waiting time.WebClient/HTTP client timeouts.
BulkheadIsolate resources so one dependency cannot consume everything.Resilience4j Bulkhead.
ObservabilityLog AggregationCentralized logging.ELK/OpenSearch-style logging stacks.
Distributed TracingTrack one request across services.Micrometer Tracing + OpenTelemetry.
MetricsMonitor application and infrastructure behavior.Micrometer + Prometheus + Grafana.
Cross-CuttingExternal ConfigurationCentralized/environment-specific configuration.Spring Cloud Config, environment variables and secret management.
Service DiscoveryLocate service instances dynamically.Eureka, Consul or platform-native discovery.
Centralized SecurityCentralized authentication and authorization.Spring Security + OAuth2/OIDC + gateway/IdP.
Data ConsistencySagaDistributed business transaction using local transactions and compensation.Kafka/RabbitMQ + orchestration/choreography.
Event SourcingPersist state changes as events.Event store/Kafka/Axon-style implementation.
CQRSSeparate command and query responsibilities.Separate read/write models or services.
MessagingMessage BrokerAsynchronous communication.Kafka/RabbitMQ.
Publish-SubscribeBroadcast events to independent consumers.@KafkaListener and Kafka topics.
Microservices rule of thumb: prefer clear business boundaries, independent ownership of data, resilient remote communication, asynchronous messaging where appropriate, and strong observability from day one.

4. SOLID Principles Overview

PrincipleDefinitionObjectiveSpring Boot ExampleRelated Concept / Pattern
SRPOne reason to change.Single responsibility.Controller → Service → Repository.Layered Architecture
OCPOpen for extension, closed for modification.Add behavior without repeatedly modifying stable code.Strategy implementations as Spring beans.Strategy
LSPSubtypes must be safely substitutable for their abstraction.Correct inheritance/polymorphism.Well-designed interfaces and implementations.Polymorphism
ISPClients should not depend on methods they do not use.Small, focused interfaces.Separate interfaces by capability.Interface Segregation
DIPHigh-level modules should depend on abstractions, not concrete implementations.Loose coupling.Constructor injection of interfaces.Dependency Injection

4.1 Easy Way to Remember SOLID

S – Single
One class should have one clear responsibility.
O – Open/Closed
Add new behavior without constantly changing stable code.
L – Liskov
A child implementation must behave correctly wherever its abstraction is expected.
I – Interface Segregation
Prefer focused interfaces over huge interfaces.
D – Dependency Inversion
Depend on interfaces/abstractions rather than concrete classes.

4.2 SOLID Example – Payment

interface PaymentProcessor {
    void pay(BigDecimal amount);
}

@Service
class CardPaymentProcessor implements PaymentProcessor {
    public void pay(BigDecimal amount) {
        // card payment
    }
}

@Service
class UpiPaymentProcessor implements PaymentProcessor {
    public void pay(BigDecimal amount) {
        // UPI payment
    }
}

@Service
class PaymentService {
    private final PaymentProcessor processor;

    PaymentService(PaymentProcessor processor) {
        this.processor = processor;
    }
}

This demonstrates abstraction, dependency injection, low coupling and a natural place to apply the Strategy pattern.

5. Core Design Principles for Spring Boot

#Design PrincipleDescription / Usage in Spring Boot
1SOLIDFoundation of object-oriented design: SRP, OCP, LSP, ISP and DIP.
2Dependency Injection (DI)Spring promotes loose coupling by injecting dependencies through constructors/setters.
3Inversion of Control (IoC)Objects do not create their dependencies; Spring controls instantiation and lifecycle.
4Separation of Concerns (SoC)Split responsibilities into layers such as Controller, Service and Repository.
5Convention over ConfigurationSpring Boot auto-configuration reduces unnecessary manual configuration.
6Don't Repeat Yourself (DRY)Reuse services, components and configuration where practical.
7High Cohesion & Low CouplingKeep related responsibilities together and minimize unnecessary dependencies.
8Configuration as CodeUse application.yml, @ConfigurationProperties and @Value rather than hardcoding environment-specific values.
9Fail FastDetect missing required beans/configuration early during startup rather than failing later.
10Profiles for EnvironmentsUse @Profile and application-{profile}.yml for dev, QA and production configuration.

6. 12-Factor App – Quick Reference

FactorDescriptionSpring Boot / Best Practice
1. CodebaseOne codebase tracked in version control, with many deploys.Git repository per microservice or clearly separated application module.
2. DependenciesExplicitly declare and isolate dependencies.pom.xml, build.gradle, Maven/Gradle dependency management.
3. ConfigStore configuration outside the codebase.Environment variables, application.yml, external configuration and secrets.
4. Backing ServicesTreat databases, caches, queues and external services as attached resources.PostgreSQL/MySQL, Redis, Kafka/RabbitMQ and external APIs configured through environment/configuration.
5. Build, Release, RunStrictly separate build, release and runtime stages.CI/CD pipeline, Maven/Gradle build, immutable artifact/container image and deployment configuration.
6. ProcessesExecute the application as stateless processes.Stateless REST APIs; persist state in DB, Redis or other external stores.
7. Port BindingExport services through port binding.Embedded Tomcat/Netty and configurable server.port.
8. ConcurrencyScale out through the process model.Multiple containers/pods, Kubernetes replicas and HPA.
9. DisposabilityFast startup and graceful shutdown.Graceful shutdown, readiness/liveness probes and short startup time.
10. Dev/Prod ParityKeep development, staging and production as similar as practical.Container images, IaC, profiles/configuration and automated CI/CD.
11. LogsTreat logs as event streams.SLF4J/Logback, structured logs, stdout/stderr and centralized collection.
12. Admin ProcessesRun administrative tasks as one-off processes.Database migrations, batch jobs, cleanup tasks and operational scripts.

7. SAGA – Distributed Business Transactions

SAGA is a sequence of local transactions. Each transaction updates data within one service and then publishes an event or command that triggers the next step. If a later step fails, compensating transactions are executed to reverse the business effects of earlier successful steps.

7.1 Why SAGA?

Distributed systems cannot easily use one ACID transaction across multiple independent services and databases.

  • Maintains eventual consistency.
  • Avoids the need for long-running distributed locks.
  • Supports independent service scaling.
  • Improves resilience through compensating transactions.
  • Works well for long-running distributed business workflows.

7.2 Two Main SAGA Styles

Choreography – Event Driven

No central controller. Each service reacts to events and publishes the next event.

OrderCreated
    ↓
InventoryReserved
    ↓
PaymentCompleted
    ↓
OrderConfirmed

Good for: relatively simple workflows with limited coordination.

Orchestration – Central Controller

A dedicated orchestrator tells each service what local transaction to execute and decides what compensation is required when something fails.

        Saga Orchestrator
        /      |       \
     Order  Inventory  Payment
        \      |       /
         Compensation

Good for: complex workflows where centralized visibility and control are important.

7.3 Example: Order Workflow

StepLocal TransactionIf SuccessfulIf Failure Occurs Later
1Create OrderPublish OrderCreatedCancel order
2Reserve InventoryPublish InventoryReservedRelease reservation
3Process PaymentPublish PaymentCompletedRefund/cancel payment
4Confirm OrderPublish OrderConfirmedCompensate previous steps if required
Important: a compensation is a business operation, not a literal database rollback. The system should define what action semantically reverses each successful step.

8. Cohesion and Coupling

Cohesion describes how strongly the responsibilities/elements inside one class or module belong together. Coupling describes how dependent one class/module is on other classes/modules.
AspectCohesionCoupling
DefinitionDegree to which elements inside a module belong together.Degree of interdependence between modules.
MeasuresHow closely related the responsibilities of a class are.How dependent classes/modules are on each other.
GoalHigh cohesion is desirable.Low coupling is desirable.
FocusWithin a class/module.Between classes/modules.
ImprovesMaintainability, readability and testability.Flexibility, reusability and modularity.
Good ExampleA class performs one closely related, well-defined business task.A class depends on interfaces/abstractions rather than concrete implementations.
Bad ExampleA class handles database, UI, validation and unrelated business logic.A class directly instantiates many concrete classes and knows their internal details.

8.1 Simple Example

High Cohesion

class InvoiceCalculator {
    calculateSubtotal();
    calculateTax();
    calculateTotal();
}

All methods are strongly related to invoice calculation.

Low Coupling

class OrderService {
    private final PaymentProcessor payment;
    // depends on abstraction
}

The service can work with different payment implementations without directly constructing them.

Interview shortcut: “Keep related things together” → High Cohesion. “Minimize dependencies between things” → Low Coupling.

9. How the Concepts Relate to Each Other

ProblemUseful Principle / PatternExample
Class has too many responsibilitiesSRP + High CohesionSeparate validation, persistence and business logic.
Too many concrete dependenciesDIP + DI + Low CouplingInject interfaces through constructors.
Need multiple algorithmsOCP + StrategyCard, UPI and wallet payment strategies.
Need to hide complex subsystemFacadeOrder service coordinating inventory, payment and shipping.
Need to add cross-cutting behaviorProxy / Decorator / AOPTransactions, caching, security and logging.
Need distributed transactionSagaOrder → Inventory → Payment → Shipping.
Remote service can failTimeout + Retry + Circuit Breaker + BulkheadResilient HTTP calls.
Need asynchronous communicationMessage Broker + Pub/Sub + Observer conceptsKafka topic with multiple consumers.
Need traceability across servicesObservability + Distributed TracingMicrometer/OpenTelemetry with centralized metrics/logs/traces.

10. Quick Interview Questions & Answers

Design Patterns

Q1. Is Spring's default bean scope Singleton?
Yes. A Spring bean is singleton-scoped by default within an application context. This is a container-managed singleton and should not be confused with manually implementing the GoF Singleton pattern.

Q2. Why is Builder useful?
It makes construction of complex objects readable and avoids constructors with many parameters, especially when many fields are optional.

Q3. Where do you see Proxy in Spring?
Spring AOP commonly uses proxies for cross-cutting concerns such as @Transactional, caching and method interception.

Q4. Strategy vs Factory?
Factory primarily decides which object to create. Strategy primarily decides which behavior/algorithm to execute.

Microservices

Q5. Why database per service?
It gives each service clear data ownership and reduces schema-level coupling. Cross-service data access is then handled through APIs/events rather than direct database sharing.

Q6. Why do we need an API Gateway?
It provides a controlled entry point for clients and can centralize routing, authentication, rate limiting, observability and other gateway concerns.

Q7. Retry vs Circuit Breaker?
Retry gives a failed transient operation another chance. Circuit Breaker prevents repeatedly calling an unhealthy dependency and helps stop cascading failures.

Q8. Why use a timeout?
Without a bounded wait, a slow downstream service can consume threads/connections and cause resource exhaustion.

Q9. What is Bulkhead?
It isolates resources so failure or saturation in one dependency/workload does not consume all resources available to unrelated operations.

SOLID & Design

Q10. What is the difference between DIP and DI?
DIP is a design principle: high-level modules should depend on abstractions. DI is a technique/framework capability used to supply those dependencies. Spring implements DI and helps us follow DIP.

Q11. What is high cohesion?
A module/class has high cohesion when its responsibilities are strongly related and focused around one clear purpose.

Q12. What is low coupling?
A module has low coupling when it has minimal unnecessary dependency on other modules and their implementation details.

Q13. Why are high cohesion and low coupling important?
Together they improve maintainability, testability, flexibility, reusability and the ability to change one part of a system without causing widespread changes.

SAGA

Q14. Does Saga provide strong ACID consistency across services?
No. Saga coordinates local transactions and normally provides eventual consistency through events and/or compensation.

Q15. Choreography vs Orchestration?
Choreography is decentralized and event-driven. Orchestration uses a central coordinator to direct the workflow and compensation steps.

Q16. Is compensation the same as rollback?
No. A database rollback reverses an uncommitted local transaction. A Saga compensation is a new business action intended to undo the business effect of an already committed transaction.

11. One-Page Mental Model

Build good classes
SOLID + High Cohesion + Low Coupling + DRY
Manage dependencies
IoC + DI + interfaces + constructor injection
Reuse proven solutions
Factory + Builder + Strategy + Adapter + Proxy + Facade + Observer
Build resilient services
Timeout + Retry + Circuit Breaker + Bulkhead
Handle distributed data
Saga + Event Sourcing + CQRS
Connect services
API Gateway + BFF + Aggregator + Message Broker + Pub/Sub
Operate production systems
12-Factor + external configuration + CI/CD + containers
Understand production behavior
Logs + Metrics + Distributed Traces + Alerts
Recommended interview answer structure: 1) Define the concept → 2) explain why it is needed → 3) give a simple real-world example → 4) show the Spring Boot implementation → 5) mention advantages/trade-offs → 6) explain where you used it in a real project.

12. Final Summary

AreaKey Takeaway
Design PrinciplesSOLID, DRY, SoC, IoC/DI, high cohesion and low coupling create maintainable code.
Design PatternsUse established patterns when they simplify a recurring design problem; do not force a pattern where simple code is clearer.
MicroservicesDesign around business capabilities and bounded contexts, with independent data ownership.
ReliabilityAssume remote dependencies can fail; use timeouts, controlled retries, circuit breakers and bulkheads.
ConsistencyUse Saga for long-running distributed workflows where a single ACID transaction is not practical.
MessagingKafka/RabbitMQ can decouple producers and consumers and enable asynchronous workflows.
ObservabilityLogs, metrics and traces together provide the evidence needed to understand production behavior.
12-FactorKeep services stateless, configurable, disposable, independently deployable and operationally friendly.