Senior Java & Microservices Interview Cheat Sheet

SOLID Principles • General Design Principles • GoF Design Patterns • 12-Factor App • Microservices Design Patterns • Architecture

Contents
  1. SOLID Principles
  2. General Design Principles
  3. GoF – Creational Patterns
  4. GoF – Structural Patterns
  5. GoF – Behavioral Patterns
  6. Most Important Interview Patterns
  7. 12-Factor App
  8. Microservices Design Patterns
  9. Resilience Patterns
  10. Distributed Transactions
  11. Service Communication
  12. Architecture Principles
  13. What Each Category Means
  14. Real-World E-Commerce Example
  15. One-Line Interview Revision
  16. Senior-Level Closing Answer

1. SOLID Principles

PrincipleFull FormInterview Definition – Single StatementSimple Example
S – SRPSingle Responsibility PrincipleA class should have one reason to change and should handle one responsibility.OrderService handles order logic while EmailService handles notifications.
O – OCPOpen/Closed PrincipleSoftware should be open for extension but closed for modification.Add CreditCardPayment and UPIPayment without changing existing payment logic.
L – LSPLiskov Substitution PrincipleA child class should be replaceable for its parent without breaking application behavior.A subtype must honor the behavioral contract of its base type.
I – ISPInterface Segregation PrincipleClients should not be forced to depend on methods they do not use.Split a large Machine interface into Printer, Scanner and Fax.
D – DIPDependency Inversion PrincipleHigh-level modules should depend on abstractions rather than concrete implementations.OrderService depends on PaymentRepository, not directly on a MySQL implementation.
Interview one-liner: “SOLID helps us build maintainable, loosely coupled, extensible and testable object-oriented applications.”

2. General Design Principles

PrincipleInterview Definition – Single StatementExample
DRYDon't Repeat Yourself – avoid duplicating business logic or knowledge.Put common validation in a shared validation component.
KISSKeep It Simple – prefer the simplest solution that satisfies the requirement.Use a simple lookup instead of an unnecessary factory hierarchy.
YAGNIYou Aren't Gonna Need It – don't implement functionality until it is actually required.Don't introduce Kafka if the current requirement only needs synchronous email.
Separation of ConcernsSeparate different responsibilities so each component focuses on a specific concern.Controller → Service → Repository.
High CohesionKeep closely related functionality together in the same module or class.Payment operations belong in payment components.
Low CouplingMinimize dependencies between components so changes remain localized.Depend on an interface rather than a concrete implementation.
Composition over InheritancePrefer composing objects instead of creating deep inheritance hierarchies.Car contains an Engine instead of extending Engine.
Program to InterfaceDepend on interfaces or abstractions rather than concrete implementations.List<String> list = new ArrayList<>();
Fail FastDetect invalid conditions as early as possible instead of allowing bad state to propagate.Validate request data at the API boundary.
Law of DemeterAn object should know only about its immediate collaborators and avoid deep navigation.Prefer a domain method over long chains such as a.getB().getC().getD().
EncapsulationHide internal implementation details and expose only what consumers need.Keep fields private and expose controlled methods.
ImmutabilityObjects should not change state after creation whenever practical.Java String and immutable value objects.
Single Source of TruthA piece of business or configuration data should have one authoritative source.Centralized configuration instead of hard-coded URLs.

3. GoF Design Patterns – Creational

PatternDefinitionJava/Spring Example
SingletonEnsures only one instance of a class exists and provides a common access point.Spring beans are singleton-scoped by default.
Factory MethodCreates objects through a method while allowing the implementation/type to vary.NotificationFactory returns Email/SMS/Push notification.
Abstract FactoryCreates families of related objects without exposing their concrete classes.A UI factory creates related Windows/Linux/Mac controls.
BuilderBuilds complex objects step by step while allowing different configurations.User.builder().name("John").age(30).build().
PrototypeCreates a new object by copying an existing object instead of constructing it from scratch.Clone a preconfigured template object.
Easy distinction: Factory = one product type; Abstract Factory = family of related products; Builder = complex construction; Prototype = copy; Singleton = one instance.

4. GoF Design Patterns – Structural

PatternInterview Definition – Single StatementExample
AdapterConverts one interface into another interface expected by the client.Adapt a legacy payment API to the application's PaymentService.
BridgeSeparates abstraction from implementation so both can evolve independently.Notification abstraction with Email/SMS implementations.
CompositeTreats individual objects and groups of objects uniformly in a tree structure.File and Folder hierarchy.
DecoratorDynamically adds responsibilities to an object without modifying its class.Java I/O stream wrappers.
FacadeProvides a simplified interface over a complex subsystem.OrderFacade coordinates inventory, payment and shipping.
FlyweightShares common state between many objects to reduce memory usage.Sharing common character/font data.
ProxyProvides a substitute object that controls access to another object.Spring AOP, transaction and security proxies.

5. GoF Design Patterns – Behavioral

PatternInterview Definition – Single StatementExample
StrategyEncapsulates interchangeable algorithms and allows the algorithm to be selected at runtime.Card, UPI and PayPal payment strategies.
ObserverAllows multiple objects to receive notifications when an object's state changes.Consumers reacting to OrderCreatedEvent.
Template MethodDefines an algorithm skeleton while allowing subclasses or steps to vary.Template-style behavior in Spring abstractions such as JdbcTemplate.
Chain of ResponsibilityPasses a request through a sequence of handlers until it is handled.Servlet filters and Spring Security filter chain.
CommandEncapsulates a request as an object so it can be queued, logged, retried or undone.CreateOrderCommand.
StateChanges an object's behavior when its internal state changes.Order: CREATED → PAID → SHIPPED → DELIVERED.
MediatorCentralizes communication between objects to reduce direct dependencies.Workflow coordinator.
IteratorProvides sequential access to collection elements without exposing internal representation.Java Iterator.
MementoCaptures object state so it can later be restored.Undo functionality.
VisitorAdds operations to object structures without modifying the element classes.Operations over different AST node types.
InterpreterDefines a representation and interpreter for a language or grammar.Expression evaluator.

6. Most Important Patterns for Senior Java Interviews

PatternRemember This Interview Statement
Strategy“Use Strategy when we have multiple interchangeable algorithms or business rules.”
Factory“Use Factory when object creation depends on runtime conditions.”
Builder“Use Builder when an object has many optional parameters or complex construction.”
Singleton“Use Singleton when exactly one shared instance is required, while avoiding unnecessary global state.”
Adapter“Use Adapter when integrating incompatible interfaces, especially legacy or third-party systems.”
Facade“Use Facade to hide subsystem complexity behind a simple interface.”
Decorator“Use Decorator to add behavior dynamically without modifying the original class.”
Proxy“Use Proxy to control access or add cross-cutting behavior such as security, transactions or caching.”
Observer“Use Observer or events when multiple consumers need to react to a change.”
Chain of Responsibility“Use it when a request should pass through multiple processing steps.”

7. 12-Factor App Principles

#FactorInterview Definition – Single StatementMicroservice Example
1CodebaseMaintain one codebase tracked in version control with multiple deployments.Same Git code deployed to DEV/UAT/PROD.
2DependenciesExplicitly declare and isolate all application dependencies.Maven pom.xml defines dependencies.
3ConfigStore environment-specific configuration outside application code.DB URLs and credentials via environment/configuration.
4Backing ServicesTreat databases, queues and external services as attached resources.PostgreSQL, Kafka and Redis endpoints are configurable.
5Build, Release, RunStrictly separate build, release and runtime stages.CI builds image → release deploys it → container runs it.
6ProcessesExecute the application as stateless processes.Store sessions in Redis rather than local process memory.
7Port BindingExport services through port binding rather than depending on an external web server.Spring Boot runs directly on port 8080.
8ConcurrencyScale applications horizontally using process models.Run multiple Order Service instances.
9DisposabilityDesign processes for fast startup and graceful shutdown.Kubernetes restarts pods and apps handle graceful termination.
10Dev/Prod ParityKeep development, staging and production environments as similar as practical.Use containers and similar infrastructure across environments.
11LogsTreat logs as event streams rather than application-managed log files.Write to stdout and centralize collection.
12Admin ProcessesRun administrative tasks as one-off processes using the same code and environment.Run database migration jobs during deployment.
Interview one-liner: “12-Factor principles help us build applications that are portable, scalable, configurable, stateless and suitable for cloud environments.”

8. Microservices Design Patterns

PatternInterview Definition – Single StatementExample
API GatewayProvides a single entry point for clients and can handle routing, authentication, rate limiting and aggregation.Spring Cloud Gateway routes /orders/** to Order Service.
BFFCreates a backend specifically tailored to the needs of each frontend or channel.Mobile BFF returns a mobile-optimized response.
Service DiscoveryAllows services to dynamically discover the network locations of service instances.Eureka or Kubernetes service discovery.
Client-Side DiscoveryThe client queries a registry and selects an available service instance.Eureka client selects an Order Service instance.
Server-Side DiscoveryThe client calls a router/load balancer that discovers the service instance.Kubernetes Service routes traffic to pods.
Circuit BreakerStops repeated calls to a failing dependency and allows the dependency time to recover.Resilience4j CircuitBreaker around Payment Service.
RetryAutomatically retries transient failures with controlled attempts and delay.Retry a temporary HTTP 503 using exponential backoff.
TimeoutLimits how long a service waits for a dependency to respond.Payment call times out after two seconds.
BulkheadIsolates resources so failure in one dependency does not exhaust the whole application.Separate resource pools for Payment and Inventory.
Rate LimitingRestricts the number of requests allowed within a specified period.100 API requests per minute per customer.
FallbackProvides an alternative response when a dependency is unavailable.Return cached recommendations.
SagaManages distributed transactions as a sequence of local transactions with compensating actions.Order → Payment → Inventory → Shipping.
CQRSSeparates read and write models when their workloads or models have different requirements.Write to PostgreSQL and serve optimized reads from Elasticsearch.
Event SourcingStores state changes as an immutable sequence of events rather than only the current state.OrderCreated, PaymentCompleted, OrderShipped.
Transactional OutboxStores business data and the outgoing event atomically in the same local database transaction.Save Order + Outbox Event together.
Inbox / Idempotent ConsumerPrevents duplicate message delivery from causing duplicate business effects.Store processed Kafka event IDs.
Strangler FigGradually replaces a legacy system by moving functionality to new services over time.Migrate Customer functionality from a monolith incrementally.
Anti-Corruption LayerProtects a domain model from another system's model by translating between them.Translate legacy DTOs into the new domain model.
AggregatorCombines data from multiple services into a single response.Order API combines Order + Customer + Payment data.
ChoreographyServices coordinate through events without a central coordinator.OrderCreated → Payment → Inventory events.
OrchestrationA central orchestrator controls the sequence of distributed operations.Order Saga orchestrator calls Payment and Inventory.
SidecarDeploys supporting functionality alongside the application as a separate process or container.Envoy sidecar for networking and observability.
Service MeshProvides infrastructure-level service communication, security and observability.Istio manages traffic between services.
Centralized ConfigurationStores environment configuration outside individual services.Spring Cloud Config Server.
Distributed TracingTracks a request across multiple services using trace/correlation IDs.OpenTelemetry + tracing backend.
Health CheckExposes health and readiness information for monitoring and orchestration.Spring Boot Actuator health endpoint.
Cache-AsideChecks cache first and loads from the database on a cache miss.Redis → DB → Redis.
Database per ServiceEach microservice owns its persistence and other services access its data through APIs/events.Order owns Order DB; Payment owns Payment DB.
Shared DatabaseMultiple services access a common database, usually as a transitional or legacy architecture.Order and Customer services share a legacy DB.
Event-Driven ArchitectureServices communicate asynchronously through events instead of requiring direct synchronous calls.Kafka OrderCreated event consumed by Inventory.

9. Resilience Patterns

Timeout ↓ Retry ↓ Circuit Breaker ↓ Fallback
PatternProblem SolvedInterview Example
TimeoutDependency takes too long.Stop waiting after two seconds.
RetryTemporary/network failure.Retry transient HTTP 503.
Circuit BreakerDependency continuously fails.Open circuit after configured failure threshold.
FallbackNeed graceful degradation.Return cached/default response.
BulkheadOne dependency consumes all resources.Isolate Payment resources.
Rate LimiterToo many requests.Limit API requests per customer.
Senior interview statement: “In microservices, I combine timeout, controlled retry with exponential backoff, circuit breaker, bulkhead and fallback rather than relying on retries alone.”

10. Distributed Transaction Patterns

PatternInterview DefinitionExample
2-Phase CommitCoordinates a distributed transaction using prepare and commit phases across participants.Multiple databases participate in one distributed transaction.
SagaBreaks a distributed transaction into local transactions with compensating actions.Payment failure → cancel order → release inventory.
Choreography SagaServices coordinate a Saga using events without a central controller.OrderCreated → PaymentCompleted → InventoryReserved.
Orchestration SagaA central orchestrator controls the distributed transaction workflow.OrderSaga calls Payment → Inventory → Shipping.
Transactional OutboxPersists domain changes and outgoing events atomically in one local DB transaction.Order + OrderCreated saved together.
IdempotencyAllows repeated execution of the same request without causing duplicate business effects.Same payment request ID does not charge twice.
Interview answer: “I generally prefer local transactions combined with Saga, Outbox and idempotent consumers because distributed transactions increase coupling and operational complexity.”

11. Synchronous vs Asynchronous Communication

ApproachDefinitionExampleWhen to Use
RESTSynchronous HTTP request/response communication.Order → Customer REST API.Immediate response required.
gRPCHigh-performance RPC communication using Protocol Buffers.Internal service-to-service API.Low latency/internal APIs.
MessagingAsynchronous communication through queues or topics.Kafka/RabbitMQ.Decoupling and eventual consistency.
Event-DrivenProducer publishes an event without requiring consumers to respond synchronously.OrderCreated.Notifications, analytics and workflows.

12. Important Architecture Principles

PrincipleInterview StatementExample
Loose CouplingServices should minimize direct dependencies on each other.Use events instead of unnecessary synchronous chains.
High CohesionEach service should contain closely related business capabilities.Payment Service owns payment functionality.
Bounded ContextA service should represent a well-defined business domain boundary.Customer, Order and Payment domains.
Autonomous ServicesA service should be independently deployable and own its business capability.Deploy Payment independently from Order.
Independent ScalabilityServices should scale according to their individual workload.Scale Search independently from Payment.
Eventual ConsistencyDistributed data may temporarily differ before asynchronous updates converge.Payment status eventually reaches Order Service.
ResilienceFailure of one service should not unnecessarily bring down the entire system.Circuit breaker isolates Payment failure.
ObservabilitySystem behavior should be understandable through logs, metrics and traces.OpenTelemetry + centralized logging + metrics.
Zero TrustEvery service request should be authenticated and authorized rather than implicitly trusted.OAuth2/JWT and service-to-service authorization.

13. SOLID vs Design Principles vs Design Patterns

ConceptWhat Is It?Easy Way to Remember
SOLIDObject-oriented design principles.How should I design classes?
DRY/KISS/YAGNIGeneral engineering principles.How do I keep code simple and maintainable?
GoF Design PatternsReusable solutions to recurring object-oriented design problems.How can I solve a common design problem?
Microservice PatternsArchitecture-level solutions for distributed systems.How should distributed services communicate and handle failures?
12-FactorCloud-native application methodology.How should I build, deploy and run cloud applications?
Architecture PrinciplesHigh-level system design guidelines.How should the overall system be structured?

14. Real-World E-Commerce Microservices Example

┌──────────────┐ │ API Gateway │ └──────┬───────┘ │ ┌────────────────┼────────────────┐ ↓ ↓ ↓ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ Order │ │ Customer │ │ Product │ │ Service │ │ Service │ │ Service │ └─────┬─────┘ └───────────┘ └───────────┘ │ ↓ ┌───────────┐ │ Payment │ │ Service │ └─────┬─────┘ │ ↓ ┌───────────┐ │ Inventory │ │ Service │ └─────┬─────┘ │ ↓ Kafka
RequirementPattern Used
Single client entry pointAPI Gateway
Find service instancesService Discovery
Payment service failureCircuit Breaker
Temporary network failureRetry + Backoff
Prevent long waitsTimeout
Isolate resourcesBulkhead
Distributed order transactionSaga
Publish OrderCreated reliablyTransactional Outbox
Prevent duplicate Kafka processingIdempotent Consumer
Asynchronous communicationEvent-Driven Architecture
Different payment algorithmsStrategy Pattern
Create payment implementationFactory Pattern
Complex Order objectBuilder Pattern
Legacy payment integrationAdapter Pattern
Hide multiple backend callsFacade / Aggregator
Configuration outside code12-Factor Config
Stateless service12-Factor Processes
Centralized logs12-Factor Logs
Horizontal scaling12-Factor Concurrency
Service healthHealth Check
Request trackingDistributed Tracing

15. One-Line Interview Revision

TopicOne-Line Interview Answer
SRPOne class should have one reason to change.
OCPExtend behavior without modifying stable existing code.
LSPSubtypes must be safely substitutable for their base types.
ISPDon't force clients to depend on interfaces they don't use.
DIPHigh-level modules should depend on abstractions, not concrete implementations.
DRYAvoid duplicating knowledge or business logic.
KISSPrefer the simplest solution that meets the requirement.
YAGNIDon't build functionality before it is actually needed.
FactoryEncapsulate object creation when the concrete type varies.
StrategyEncapsulate interchangeable algorithms behind a common interface.
BuilderConstruct complex objects step by step.
AdapterMake incompatible interfaces work together.
FacadeHide complex subsystem interactions behind a simple interface.
DecoratorDynamically add behavior without changing the original class.
ProxyControl access to another object and/or add cross-cutting behavior.
ObserverNotify multiple consumers when something changes.
API GatewayProvide a centralized entry point for clients to access microservices.
Circuit BreakerStop repeatedly calling a failing dependency and allow recovery.
RetryReattempt transient failures using a controlled retry policy.
BulkheadIsolate resources to prevent cascading failures.
SagaManage distributed transactions using local transactions and compensation.
OutboxReliably publish events by storing them atomically with business data.
IdempotencyMake repeated requests produce the same intended business result.
CQRSSeparate read and write models when their requirements differ.
Event SourcingStore state as an immutable sequence of business events.
Service DiscoveryDynamically locate available service instances.
BFFProvide a backend optimized for a specific frontend or channel.
Strangler FigGradually replace a legacy system with new services.
Anti-Corruption LayerPrevent an external or legacy domain model from contaminating the internal domain model.
Database per ServiceEach microservice owns and controls its persistence.
Eventual ConsistencyDistributed data may temporarily differ before converging.
12-Factor ConfigKeep environment-specific configuration outside application code.
12-Factor ProcessesKeep application processes stateless and horizontally scalable.
12-Factor LogsTreat logs as event streams and let the environment aggregate them.
ObservabilityUnderstand system behavior using logs, metrics and distributed traces.

16. Strong Senior-Level Closing Answer

“In my microservices design, I use SOLID principles at the class level, patterns such as Strategy, Factory, Builder and Adapter at the application level, and microservice patterns such as API Gateway, Circuit Breaker, Saga, Transactional Outbox, Idempotency and Event-Driven Communication at the architecture level. I also follow 12-Factor principles for externalized configuration, stateless processes, portability, scalability and cloud-native deployment. The overall goal is to achieve low coupling, high cohesion, independent deployability, resilience, observability and maintainability.”