1. How These Concepts Fit Together
SOLID, DRY, high cohesion, low coupling, DI/IoC.
Creational, Structural and Behavioral GoF patterns.
API Gateway, BFF, Saga, Circuit Breaker, Bulkhead, Retry.
Configuration, observability, containers, CI/CD and 12-Factor practices.
2. Design Patterns at a Glance
| Pattern | Type | Spring Boot Usage | Typical Example / Purpose |
|---|---|---|---|
| Singleton | Creational | @Component, @Service, @Repository | Spring beans are singleton-scoped by default: one bean instance per application context. |
| Factory Method | Creational | ApplicationContext, BeanFactory, @Bean | Create objects dynamically while hiding creation logic. |
| Builder | Creational | DTOs, response objects, Lombok @Builder | UserResponse.builder().id(1).name("John").build() |
| Prototype | Creational | @Scope("prototype") | A new bean instance is created whenever it is requested from the container. |
| Adapter | Structural | Spring Security, legacy/external integrations | Convert an external API/model into an internal domain model. |
| Decorator | Structural | Logging, validation, wrappers, servlet filters | Add behavior without modifying the original object. |
| Proxy | Structural | @Transactional, @Cacheable, Spring AOP | Spring creates proxies to apply transactions, caching, security and other cross-cutting behavior. |
| Facade | Structural | Service layer, API gateway | Expose a simple interface over multiple backend services. |
| Template Method | Behavioral | JdbcTemplate, RestTemplate, transaction templates | Define a common workflow while allowing specific steps to vary. |
| Strategy | Behavioral | Payment, authentication, notification services | Select an algorithm/implementation dynamically at runtime. |
| Observer | Behavioral | ApplicationEventPublisher, @EventListener | Publish an event and notify independent subscribers. |
| Command | Behavioral | CQRS, background jobs, task queues | Encapsulate an action/request as an object. |
| Chain of Responsibility | Behavioral | Servlet filters, Spring Security filter chain | Pass a request through multiple processing steps. |
| Iterator | Behavioral | Java Collections, Streams, JPA paging | Traverse a collection sequentially without exposing its internal representation. |
| Interpreter | Behavioral | Expression/rule engines, DSL parsing | Interpret expressions or business rules dynamically. |
2.1 Creational Patterns – Simple Understanding
“Give me the same managed instance.” Useful for stateless Spring services and shared infrastructure components.
“Decide which object to create.” Useful when the concrete implementation depends on type, configuration or runtime input.
“Build a complex object step by step.” Especially useful for immutable DTOs with many optional fields.
“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
| Category | Pattern | Description | Typical Spring / Platform Implementation |
|---|---|---|---|
| Decomposition | Business Capability | Split services by business domain/capability. | Separate services such as order-service and user-service. |
| Subdomain / Bounded Context | Define clear DDD business boundaries. | Inventory, Catalog, Payment and Shipping contexts. | |
| Integration | API Gateway | Single entry point for clients. | Spring Cloud Gateway. |
| Aggregator | Combine multiple service responses. | Composite REST service or gateway aggregation. | |
| BFF | Separate API optimized for each client type. | Web BFF and Mobile BFF. | |
| Database | Database per Service | Each service owns its data. | Spring Data JPA with separate database/schema. |
| Shared Database | Multiple services share a schema; generally increases coupling. | Legacy-system or migration scenarios. | |
| Reliability | Circuit Breaker | Prevent cascading failures. | Resilience4j CircuitBreaker. |
| Retry | Retry transient failures carefully. | Resilience4j Retry / Spring Retry. | |
| Timeout | Limit remote-call waiting time. | WebClient/HTTP client timeouts. | |
| Bulkhead | Isolate resources so one dependency cannot consume everything. | Resilience4j Bulkhead. | |
| Observability | Log Aggregation | Centralized logging. | ELK/OpenSearch-style logging stacks. |
| Distributed Tracing | Track one request across services. | Micrometer Tracing + OpenTelemetry. | |
| Metrics | Monitor application and infrastructure behavior. | Micrometer + Prometheus + Grafana. | |
| Cross-Cutting | External Configuration | Centralized/environment-specific configuration. | Spring Cloud Config, environment variables and secret management. |
| Service Discovery | Locate service instances dynamically. | Eureka, Consul or platform-native discovery. | |
| Centralized Security | Centralized authentication and authorization. | Spring Security + OAuth2/OIDC + gateway/IdP. | |
| Data Consistency | Saga | Distributed business transaction using local transactions and compensation. | Kafka/RabbitMQ + orchestration/choreography. |
| Event Sourcing | Persist state changes as events. | Event store/Kafka/Axon-style implementation. | |
| CQRS | Separate command and query responsibilities. | Separate read/write models or services. | |
| Messaging | Message Broker | Asynchronous communication. | Kafka/RabbitMQ. |
| Publish-Subscribe | Broadcast events to independent consumers. | @KafkaListener and Kafka topics. |
4. SOLID Principles Overview
| Principle | Definition | Objective | Spring Boot Example | Related Concept / Pattern |
|---|---|---|---|---|
| SRP | One reason to change. | Single responsibility. | Controller → Service → Repository. | Layered Architecture |
| OCP | Open for extension, closed for modification. | Add behavior without repeatedly modifying stable code. | Strategy implementations as Spring beans. | Strategy |
| LSP | Subtypes must be safely substitutable for their abstraction. | Correct inheritance/polymorphism. | Well-designed interfaces and implementations. | Polymorphism |
| ISP | Clients should not depend on methods they do not use. | Small, focused interfaces. | Separate interfaces by capability. | Interface Segregation |
| DIP | High-level modules should depend on abstractions, not concrete implementations. | Loose coupling. | Constructor injection of interfaces. | Dependency Injection |
4.1 Easy Way to Remember SOLID
One class should have one clear responsibility.
Add new behavior without constantly changing stable code.
A child implementation must behave correctly wherever its abstraction is expected.
Prefer focused interfaces over huge interfaces.
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 Principle | Description / Usage in Spring Boot |
|---|---|---|
| 1 | SOLID | Foundation of object-oriented design: SRP, OCP, LSP, ISP and DIP. |
| 2 | Dependency Injection (DI) | Spring promotes loose coupling by injecting dependencies through constructors/setters. |
| 3 | Inversion of Control (IoC) | Objects do not create their dependencies; Spring controls instantiation and lifecycle. |
| 4 | Separation of Concerns (SoC) | Split responsibilities into layers such as Controller, Service and Repository. |
| 5 | Convention over Configuration | Spring Boot auto-configuration reduces unnecessary manual configuration. |
| 6 | Don't Repeat Yourself (DRY) | Reuse services, components and configuration where practical. |
| 7 | High Cohesion & Low Coupling | Keep related responsibilities together and minimize unnecessary dependencies. |
| 8 | Configuration as Code | Use application.yml, @ConfigurationProperties and @Value rather than hardcoding environment-specific values. |
| 9 | Fail Fast | Detect missing required beans/configuration early during startup rather than failing later. |
| 10 | Profiles for Environments | Use @Profile and application-{profile}.yml for dev, QA and production configuration. |
6. 12-Factor App – Quick Reference
| Factor | Description | Spring Boot / Best Practice |
|---|---|---|
| 1. Codebase | One codebase tracked in version control, with many deploys. | Git repository per microservice or clearly separated application module. |
| 2. Dependencies | Explicitly declare and isolate dependencies. | pom.xml, build.gradle, Maven/Gradle dependency management. |
| 3. Config | Store configuration outside the codebase. | Environment variables, application.yml, external configuration and secrets. |
| 4. Backing Services | Treat databases, caches, queues and external services as attached resources. | PostgreSQL/MySQL, Redis, Kafka/RabbitMQ and external APIs configured through environment/configuration. |
| 5. Build, Release, Run | Strictly separate build, release and runtime stages. | CI/CD pipeline, Maven/Gradle build, immutable artifact/container image and deployment configuration. |
| 6. Processes | Execute the application as stateless processes. | Stateless REST APIs; persist state in DB, Redis or other external stores. |
| 7. Port Binding | Export services through port binding. | Embedded Tomcat/Netty and configurable server.port. |
| 8. Concurrency | Scale out through the process model. | Multiple containers/pods, Kubernetes replicas and HPA. |
| 9. Disposability | Fast startup and graceful shutdown. | Graceful shutdown, readiness/liveness probes and short startup time. |
| 10. Dev/Prod Parity | Keep development, staging and production as similar as practical. | Container images, IaC, profiles/configuration and automated CI/CD. |
| 11. Logs | Treat logs as event streams. | SLF4J/Logback, structured logs, stdout/stderr and centralized collection. |
| 12. Admin Processes | Run administrative tasks as one-off processes. | Database migrations, batch jobs, cleanup tasks and operational scripts. |
7. SAGA – Distributed Business Transactions
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
| Step | Local Transaction | If Successful | If Failure Occurs Later |
|---|---|---|---|
| 1 | Create Order | Publish OrderCreated | Cancel order |
| 2 | Reserve Inventory | Publish InventoryReserved | Release reservation |
| 3 | Process Payment | Publish PaymentCompleted | Refund/cancel payment |
| 4 | Confirm Order | Publish OrderConfirmed | Compensate previous steps if required |
8. Cohesion and Coupling
| Aspect | Cohesion | Coupling |
|---|---|---|
| Definition | Degree to which elements inside a module belong together. | Degree of interdependence between modules. |
| Measures | How closely related the responsibilities of a class are. | How dependent classes/modules are on each other. |
| Goal | High cohesion is desirable. | Low coupling is desirable. |
| Focus | Within a class/module. | Between classes/modules. |
| Improves | Maintainability, readability and testability. | Flexibility, reusability and modularity. |
| Good Example | A class performs one closely related, well-defined business task. | A class depends on interfaces/abstractions rather than concrete implementations. |
| Bad Example | A 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.
9. How the Concepts Relate to Each Other
| Problem | Useful Principle / Pattern | Example |
|---|---|---|
| Class has too many responsibilities | SRP + High Cohesion | Separate validation, persistence and business logic. |
| Too many concrete dependencies | DIP + DI + Low Coupling | Inject interfaces through constructors. |
| Need multiple algorithms | OCP + Strategy | Card, UPI and wallet payment strategies. |
| Need to hide complex subsystem | Facade | Order service coordinating inventory, payment and shipping. |
| Need to add cross-cutting behavior | Proxy / Decorator / AOP | Transactions, caching, security and logging. |
| Need distributed transaction | Saga | Order → Inventory → Payment → Shipping. |
| Remote service can fail | Timeout + Retry + Circuit Breaker + Bulkhead | Resilient HTTP calls. |
| Need asynchronous communication | Message Broker + Pub/Sub + Observer concepts | Kafka topic with multiple consumers. |
| Need traceability across services | Observability + Distributed Tracing | Micrometer/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
SOLID + High Cohesion + Low Coupling + DRY
IoC + DI + interfaces + constructor injection
Factory + Builder + Strategy + Adapter + Proxy + Facade + Observer
Timeout + Retry + Circuit Breaker + Bulkhead
Saga + Event Sourcing + CQRS
API Gateway + BFF + Aggregator + Message Broker + Pub/Sub
12-Factor + external configuration + CI/CD + containers
Logs + Metrics + Distributed Traces + Alerts
12. Final Summary
| Area | Key Takeaway |
|---|---|
| Design Principles | SOLID, DRY, SoC, IoC/DI, high cohesion and low coupling create maintainable code. |
| Design Patterns | Use established patterns when they simplify a recurring design problem; do not force a pattern where simple code is clearer. |
| Microservices | Design around business capabilities and bounded contexts, with independent data ownership. |
| Reliability | Assume remote dependencies can fail; use timeouts, controlled retries, circuit breakers and bulkheads. |
| Consistency | Use Saga for long-running distributed workflows where a single ACID transaction is not practical. |
| Messaging | Kafka/RabbitMQ can decouple producers and consumers and enable asynchronous workflows. |
| Observability | Logs, metrics and traces together provide the evidence needed to understand production behavior. |
| 12-Factor | Keep services stateless, configurable, disposable, independently deployable and operationally friendly. |