Java Spring Boot & Microservices – Quick Reference

Java Spring Boot & Microservices – Quick Reference

1. Design Patterns at a Glance

PatternTypeSpring Boot UsageTypical Example
SingletonCreational@Component, @Service, @Repository beansSpring creates one bean instance per application context by default.
Factory MethodCreationalApplicationContext, BeanFactory, @BeanCreate objects dynamically without exposing creation logic.
BuilderCreationalDTOs, response objects, Lombok @BuilderUserResponse.builder().id(1).name("John").build()
PrototypeCreational@Scope("prototype")Create a new bean instance 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 changing the original object.
ProxyStructural@Transactional, @Cacheable, Spring AOPSpring creates a proxy to apply transactions, caching, security, etc.
FacadeStructuralService layer, API gatewayExpose a simple interface over multiple backend services.
Template MethodBehavioralJdbcTemplate, RestTemplate, TransactionTemplateDefine 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 subscribers.
CommandBehavioralCQRS, background jobs, task queuesEncapsulate an action 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 internals.
InterpreterBehavioralExpression/rule engines, DSL parsingInterpret expressions or business rules dynamically.

2. Microservices Design Patterns – Complete Overview

Pattern CategoryDesign PatternDescriptionSpring Boot Implementation
DecompositionBusiness CapabilitySplit services by business domain/capability.Separate projects: order-service, user-service.
Subdomain / Bounded ContextDefine clear DDD business boundaries.Inventory, Catalog, Payment, Shipping contexts.
IntegrationAPI GatewaySingle entry point for clients.Spring Cloud Gateway.
AggregatorCombine multiple service responses.Composite REST service / gateway aggregation.
BFFSeparate API optimized for each client.Web BFF and Mobile BFF.
DatabaseDatabase per ServiceIndependent data ownership.Spring Data JPA with separate DB/schema.
Shared DatabaseMultiple services share schema; generally creates coupling.Legacy systems / migration scenarios.
ReliabilityCircuit BreakerPrevent cascading failures.Resilience4j CircuitBreaker.
RetryRetry transient failures.Resilience4j Retry / Spring Retry.
TimeoutLimit remote-call waiting time.WebClient/HTTP client timeouts.
BulkheadIsolate resources.Resilience4j Bulkhead.
ObservabilityLog AggregationCentralized logging.ELK/OpenSearch-style stacks.
Distributed TracingTrack one request across services.Micrometer Tracing + OpenTelemetry.
MetricsMonitor application behavior.Micrometer + Prometheus + Grafana.
Cross-CuttingExternal ConfigurationCentralized/environment-specific configuration.Spring Cloud Config / environment config.
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.

3. SOLID Principles Overview

PrincipleDefinitionObjectiveSpring Boot ExampleRelated Pattern / Concept
SRPOne reason to change.Single responsibility.Controller → Service → RepositoryLayered 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. Two Types of SAGA

TypeSimple MeaningWho Decides the Next Step?Best Fit
ChoreographyNo central coordinator. Services react to events.Each participating service.Smaller/simple event-driven workflows.
OrchestrationA central Saga Orchestrator controls the workflow.Orchestrator.Complex workflows requiring centralized visibility/control.

5. 12-Factor App – Quick Reference

FactorDescriptionSpring Boot Implementation / 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, Spring configuration mechanisms, external config/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, deployment configuration.
6. ProcessesExecute the application as stateless processes.Stateless REST APIs; persist state in databases, Redis or other external stores.
7. Port BindingExport services through port binding.Embedded server such as 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.Spring Boot graceful shutdown, readiness/liveness probes, short startup time.
10. Dev/Prod ParityKeep development, staging and production as similar as practical.Container images, infrastructure-as-code, profiles/configuration and automated CI/CD.
11. LogsTreat logs as event streams.SLF4J/Logback, structured logs, stdout/stderr and centralized log collection.
12. Admin ProcessesRun administrative/management tasks as one-off processes.Database migrations, batch jobs, cleanup tasks and operational scripts.

6. What is Cohesion and Coupling

Cohesion is how strongly the components of a single module/class are related to each other.

Coupling is about how dependent one module/class is on another.

AspectCohesionCoupling
DefinitionDegree to which elements inside a module belong together
Measures how closely related the responsibilities of a single class are.
Degree of interdependence between modules
Measures how dependent classes are on each other.
GoalHigh cohesion is desirableLow coupling is desirable
FocusWithin a class/moduleBetween classes/modules
ImprovesMaintainability, readability, testabilityFlexibility, reusability, modularity
Good ExampleA class that performs a single, well-defined taskA class that depends on interfaces, not implementations
Bad ExampleA class that handles DB, UI, and business logicA class that directly instantiates and uses other classes

7. Grafana Dashboard Panels

PanelPurposeInterpretation
LatencyResponse TimeSpike indicates performance degradation
ThroughputRequests per secondDrop indicates load handling issue
Error RateFailed RequestsIncrease indicates failures
CPUResource ConsumptionHigh CPU means overload
MemoryHeap UsageContinuous increase may indicate leak
Pod HealthRestart CountFrequent restarts indicate instability

8. Important Prometheus Metrics

MetricQueryPurpose
Throughputsum(increase(http_server_requests_seconds_count[1m]))Total Requests
Latencyrate(http_server_requests_seconds_sum[5m])Response Time
CPUprocess_cpu_usageApplication CPU Usage
Memoryjvm_memory_used_bytesHeap Usage
DB Pool Usagehikaricp_connections_active / hikaricp_connections_maxConnection Pool Saturation