SOLID Principles • General Design Principles • GoF Design Patterns • 12-Factor App • Microservices Design Patterns • Architecture
| Principle | Full Form | Interview Definition – Single Statement | Simple Example |
|---|---|---|---|
| S – SRP | Single Responsibility Principle | A class should have one reason to change and should handle one responsibility. | OrderService handles order logic while EmailService handles notifications. |
| O – OCP | Open/Closed Principle | Software should be open for extension but closed for modification. | Add CreditCardPayment and UPIPayment without changing existing payment logic. |
| L – LSP | Liskov Substitution Principle | A child class should be replaceable for its parent without breaking application behavior. | A subtype must honor the behavioral contract of its base type. |
| I – ISP | Interface Segregation Principle | Clients should not be forced to depend on methods they do not use. | Split a large Machine interface into Printer, Scanner and Fax. |
| D – DIP | Dependency Inversion Principle | High-level modules should depend on abstractions rather than concrete implementations. | OrderService depends on PaymentRepository, not directly on a MySQL implementation. |
| Principle | Interview Definition – Single Statement | Example |
|---|---|---|
| DRY | Don't Repeat Yourself – avoid duplicating business logic or knowledge. | Put common validation in a shared validation component. |
| KISS | Keep It Simple – prefer the simplest solution that satisfies the requirement. | Use a simple lookup instead of an unnecessary factory hierarchy. |
| YAGNI | You 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 Concerns | Separate different responsibilities so each component focuses on a specific concern. | Controller → Service → Repository. |
| High Cohesion | Keep closely related functionality together in the same module or class. | Payment operations belong in payment components. |
| Low Coupling | Minimize dependencies between components so changes remain localized. | Depend on an interface rather than a concrete implementation. |
| Composition over Inheritance | Prefer composing objects instead of creating deep inheritance hierarchies. | Car contains an Engine instead of extending Engine. |
| Program to Interface | Depend on interfaces or abstractions rather than concrete implementations. | List<String> list = new ArrayList<>(); |
| Fail Fast | Detect invalid conditions as early as possible instead of allowing bad state to propagate. | Validate request data at the API boundary. |
| Law of Demeter | An 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(). |
| Encapsulation | Hide internal implementation details and expose only what consumers need. | Keep fields private and expose controlled methods. |
| Immutability | Objects should not change state after creation whenever practical. | Java String and immutable value objects. |
| Single Source of Truth | A piece of business or configuration data should have one authoritative source. | Centralized configuration instead of hard-coded URLs. |
| Pattern | Definition | Java/Spring Example |
|---|---|---|
| Singleton | Ensures only one instance of a class exists and provides a common access point. | Spring beans are singleton-scoped by default. |
| Factory Method | Creates objects through a method while allowing the implementation/type to vary. | NotificationFactory returns Email/SMS/Push notification. |
| Abstract Factory | Creates families of related objects without exposing their concrete classes. | A UI factory creates related Windows/Linux/Mac controls. |
| Builder | Builds complex objects step by step while allowing different configurations. | User.builder().name("John").age(30).build(). |
| Prototype | Creates a new object by copying an existing object instead of constructing it from scratch. | Clone a preconfigured template object. |
| Pattern | Interview Definition – Single Statement | Example |
|---|---|---|
| Adapter | Converts one interface into another interface expected by the client. | Adapt a legacy payment API to the application's PaymentService. |
| Bridge | Separates abstraction from implementation so both can evolve independently. | Notification abstraction with Email/SMS implementations. |
| Composite | Treats individual objects and groups of objects uniformly in a tree structure. | File and Folder hierarchy. |
| Decorator | Dynamically adds responsibilities to an object without modifying its class. | Java I/O stream wrappers. |
| Facade | Provides a simplified interface over a complex subsystem. | OrderFacade coordinates inventory, payment and shipping. |
| Flyweight | Shares common state between many objects to reduce memory usage. | Sharing common character/font data. |
| Proxy | Provides a substitute object that controls access to another object. | Spring AOP, transaction and security proxies. |
| Pattern | Interview Definition – Single Statement | Example |
|---|---|---|
| Strategy | Encapsulates interchangeable algorithms and allows the algorithm to be selected at runtime. | Card, UPI and PayPal payment strategies. |
| Observer | Allows multiple objects to receive notifications when an object's state changes. | Consumers reacting to OrderCreatedEvent. |
| Template Method | Defines an algorithm skeleton while allowing subclasses or steps to vary. | Template-style behavior in Spring abstractions such as JdbcTemplate. |
| Chain of Responsibility | Passes a request through a sequence of handlers until it is handled. | Servlet filters and Spring Security filter chain. |
| Command | Encapsulates a request as an object so it can be queued, logged, retried or undone. | CreateOrderCommand. |
| State | Changes an object's behavior when its internal state changes. | Order: CREATED → PAID → SHIPPED → DELIVERED. |
| Mediator | Centralizes communication between objects to reduce direct dependencies. | Workflow coordinator. |
| Iterator | Provides sequential access to collection elements without exposing internal representation. | Java Iterator. |
| Memento | Captures object state so it can later be restored. | Undo functionality. |
| Visitor | Adds operations to object structures without modifying the element classes. | Operations over different AST node types. |
| Interpreter | Defines a representation and interpreter for a language or grammar. | Expression evaluator. |
| Pattern | Remember 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.” |
| # | Factor | Interview Definition – Single Statement | Microservice Example |
|---|---|---|---|
| 1 | Codebase | Maintain one codebase tracked in version control with multiple deployments. | Same Git code deployed to DEV/UAT/PROD. |
| 2 | Dependencies | Explicitly declare and isolate all application dependencies. | Maven pom.xml defines dependencies. |
| 3 | Config | Store environment-specific configuration outside application code. | DB URLs and credentials via environment/configuration. |
| 4 | Backing Services | Treat databases, queues and external services as attached resources. | PostgreSQL, Kafka and Redis endpoints are configurable. |
| 5 | Build, Release, Run | Strictly separate build, release and runtime stages. | CI builds image → release deploys it → container runs it. |
| 6 | Processes | Execute the application as stateless processes. | Store sessions in Redis rather than local process memory. |
| 7 | Port Binding | Export services through port binding rather than depending on an external web server. | Spring Boot runs directly on port 8080. |
| 8 | Concurrency | Scale applications horizontally using process models. | Run multiple Order Service instances. |
| 9 | Disposability | Design processes for fast startup and graceful shutdown. | Kubernetes restarts pods and apps handle graceful termination. |
| 10 | Dev/Prod Parity | Keep development, staging and production environments as similar as practical. | Use containers and similar infrastructure across environments. |
| 11 | Logs | Treat logs as event streams rather than application-managed log files. | Write to stdout and centralize collection. |
| 12 | Admin Processes | Run administrative tasks as one-off processes using the same code and environment. | Run database migration jobs during deployment. |
| Pattern | Interview Definition – Single Statement | Example |
|---|---|---|
| API Gateway | Provides a single entry point for clients and can handle routing, authentication, rate limiting and aggregation. | Spring Cloud Gateway routes /orders/** to Order Service. |
| BFF | Creates a backend specifically tailored to the needs of each frontend or channel. | Mobile BFF returns a mobile-optimized response. |
| Service Discovery | Allows services to dynamically discover the network locations of service instances. | Eureka or Kubernetes service discovery. |
| Client-Side Discovery | The client queries a registry and selects an available service instance. | Eureka client selects an Order Service instance. |
| Server-Side Discovery | The client calls a router/load balancer that discovers the service instance. | Kubernetes Service routes traffic to pods. |
| Circuit Breaker | Stops repeated calls to a failing dependency and allows the dependency time to recover. | Resilience4j CircuitBreaker around Payment Service. |
| Retry | Automatically retries transient failures with controlled attempts and delay. | Retry a temporary HTTP 503 using exponential backoff. |
| Timeout | Limits how long a service waits for a dependency to respond. | Payment call times out after two seconds. |
| Bulkhead | Isolates resources so failure in one dependency does not exhaust the whole application. | Separate resource pools for Payment and Inventory. |
| Rate Limiting | Restricts the number of requests allowed within a specified period. | 100 API requests per minute per customer. |
| Fallback | Provides an alternative response when a dependency is unavailable. | Return cached recommendations. |
| Saga | Manages distributed transactions as a sequence of local transactions with compensating actions. | Order → Payment → Inventory → Shipping. |
| CQRS | Separates read and write models when their workloads or models have different requirements. | Write to PostgreSQL and serve optimized reads from Elasticsearch. |
| Event Sourcing | Stores state changes as an immutable sequence of events rather than only the current state. | OrderCreated, PaymentCompleted, OrderShipped. |
| Transactional Outbox | Stores business data and the outgoing event atomically in the same local database transaction. | Save Order + Outbox Event together. |
| Inbox / Idempotent Consumer | Prevents duplicate message delivery from causing duplicate business effects. | Store processed Kafka event IDs. |
| Strangler Fig | Gradually replaces a legacy system by moving functionality to new services over time. | Migrate Customer functionality from a monolith incrementally. |
| Anti-Corruption Layer | Protects a domain model from another system's model by translating between them. | Translate legacy DTOs into the new domain model. |
| Aggregator | Combines data from multiple services into a single response. | Order API combines Order + Customer + Payment data. |
| Choreography | Services coordinate through events without a central coordinator. | OrderCreated → Payment → Inventory events. |
| Orchestration | A central orchestrator controls the sequence of distributed operations. | Order Saga orchestrator calls Payment and Inventory. |
| Sidecar | Deploys supporting functionality alongside the application as a separate process or container. | Envoy sidecar for networking and observability. |
| Service Mesh | Provides infrastructure-level service communication, security and observability. | Istio manages traffic between services. |
| Centralized Configuration | Stores environment configuration outside individual services. | Spring Cloud Config Server. |
| Distributed Tracing | Tracks a request across multiple services using trace/correlation IDs. | OpenTelemetry + tracing backend. |
| Health Check | Exposes health and readiness information for monitoring and orchestration. | Spring Boot Actuator health endpoint. |
| Cache-Aside | Checks cache first and loads from the database on a cache miss. | Redis → DB → Redis. |
| Database per Service | Each microservice owns its persistence and other services access its data through APIs/events. | Order owns Order DB; Payment owns Payment DB. |
| Shared Database | Multiple services access a common database, usually as a transitional or legacy architecture. | Order and Customer services share a legacy DB. |
| Event-Driven Architecture | Services communicate asynchronously through events instead of requiring direct synchronous calls. | Kafka OrderCreated event consumed by Inventory. |
| Pattern | Problem Solved | Interview Example |
|---|---|---|
| Timeout | Dependency takes too long. | Stop waiting after two seconds. |
| Retry | Temporary/network failure. | Retry transient HTTP 503. |
| Circuit Breaker | Dependency continuously fails. | Open circuit after configured failure threshold. |
| Fallback | Need graceful degradation. | Return cached/default response. |
| Bulkhead | One dependency consumes all resources. | Isolate Payment resources. |
| Rate Limiter | Too many requests. | Limit API requests per customer. |
| Pattern | Interview Definition | Example |
|---|---|---|
| 2-Phase Commit | Coordinates a distributed transaction using prepare and commit phases across participants. | Multiple databases participate in one distributed transaction. |
| Saga | Breaks a distributed transaction into local transactions with compensating actions. | Payment failure → cancel order → release inventory. |
| Choreography Saga | Services coordinate a Saga using events without a central controller. | OrderCreated → PaymentCompleted → InventoryReserved. |
| Orchestration Saga | A central orchestrator controls the distributed transaction workflow. | OrderSaga calls Payment → Inventory → Shipping. |
| Transactional Outbox | Persists domain changes and outgoing events atomically in one local DB transaction. | Order + OrderCreated saved together. |
| Idempotency | Allows repeated execution of the same request without causing duplicate business effects. | Same payment request ID does not charge twice. |
| Approach | Definition | Example | When to Use |
|---|---|---|---|
| REST | Synchronous HTTP request/response communication. | Order → Customer REST API. | Immediate response required. |
| gRPC | High-performance RPC communication using Protocol Buffers. | Internal service-to-service API. | Low latency/internal APIs. |
| Messaging | Asynchronous communication through queues or topics. | Kafka/RabbitMQ. | Decoupling and eventual consistency. |
| Event-Driven | Producer publishes an event without requiring consumers to respond synchronously. | OrderCreated. | Notifications, analytics and workflows. |
| Principle | Interview Statement | Example |
|---|---|---|
| Loose Coupling | Services should minimize direct dependencies on each other. | Use events instead of unnecessary synchronous chains. |
| High Cohesion | Each service should contain closely related business capabilities. | Payment Service owns payment functionality. |
| Bounded Context | A service should represent a well-defined business domain boundary. | Customer, Order and Payment domains. |
| Autonomous Services | A service should be independently deployable and own its business capability. | Deploy Payment independently from Order. |
| Independent Scalability | Services should scale according to their individual workload. | Scale Search independently from Payment. |
| Eventual Consistency | Distributed data may temporarily differ before asynchronous updates converge. | Payment status eventually reaches Order Service. |
| Resilience | Failure of one service should not unnecessarily bring down the entire system. | Circuit breaker isolates Payment failure. |
| Observability | System behavior should be understandable through logs, metrics and traces. | OpenTelemetry + centralized logging + metrics. |
| Zero Trust | Every service request should be authenticated and authorized rather than implicitly trusted. | OAuth2/JWT and service-to-service authorization. |
| Concept | What Is It? | Easy Way to Remember |
|---|---|---|
| SOLID | Object-oriented design principles. | How should I design classes? |
| DRY/KISS/YAGNI | General engineering principles. | How do I keep code simple and maintainable? |
| GoF Design Patterns | Reusable solutions to recurring object-oriented design problems. | How can I solve a common design problem? |
| Microservice Patterns | Architecture-level solutions for distributed systems. | How should distributed services communicate and handle failures? |
| 12-Factor | Cloud-native application methodology. | How should I build, deploy and run cloud applications? |
| Architecture Principles | High-level system design guidelines. | How should the overall system be structured? |
| Requirement | Pattern Used |
|---|---|
| Single client entry point | API Gateway |
| Find service instances | Service Discovery |
| Payment service failure | Circuit Breaker |
| Temporary network failure | Retry + Backoff |
| Prevent long waits | Timeout |
| Isolate resources | Bulkhead |
| Distributed order transaction | Saga |
| Publish OrderCreated reliably | Transactional Outbox |
| Prevent duplicate Kafka processing | Idempotent Consumer |
| Asynchronous communication | Event-Driven Architecture |
| Different payment algorithms | Strategy Pattern |
| Create payment implementation | Factory Pattern |
| Complex Order object | Builder Pattern |
| Legacy payment integration | Adapter Pattern |
| Hide multiple backend calls | Facade / Aggregator |
| Configuration outside code | 12-Factor Config |
| Stateless service | 12-Factor Processes |
| Centralized logs | 12-Factor Logs |
| Horizontal scaling | 12-Factor Concurrency |
| Service health | Health Check |
| Request tracking | Distributed Tracing |
| Topic | One-Line Interview Answer |
|---|---|
| SRP | One class should have one reason to change. |
| OCP | Extend behavior without modifying stable existing code. |
| LSP | Subtypes must be safely substitutable for their base types. |
| ISP | Don't force clients to depend on interfaces they don't use. |
| DIP | High-level modules should depend on abstractions, not concrete implementations. |
| DRY | Avoid duplicating knowledge or business logic. |
| KISS | Prefer the simplest solution that meets the requirement. |
| YAGNI | Don't build functionality before it is actually needed. |
| Factory | Encapsulate object creation when the concrete type varies. |
| Strategy | Encapsulate interchangeable algorithms behind a common interface. |
| Builder | Construct complex objects step by step. |
| Adapter | Make incompatible interfaces work together. |
| Facade | Hide complex subsystem interactions behind a simple interface. |
| Decorator | Dynamically add behavior without changing the original class. |
| Proxy | Control access to another object and/or add cross-cutting behavior. |
| Observer | Notify multiple consumers when something changes. |
| API Gateway | Provide a centralized entry point for clients to access microservices. |
| Circuit Breaker | Stop repeatedly calling a failing dependency and allow recovery. |
| Retry | Reattempt transient failures using a controlled retry policy. |
| Bulkhead | Isolate resources to prevent cascading failures. |
| Saga | Manage distributed transactions using local transactions and compensation. |
| Outbox | Reliably publish events by storing them atomically with business data. |
| Idempotency | Make repeated requests produce the same intended business result. |
| CQRS | Separate read and write models when their requirements differ. |
| Event Sourcing | Store state as an immutable sequence of business events. |
| Service Discovery | Dynamically locate available service instances. |
| BFF | Provide a backend optimized for a specific frontend or channel. |
| Strangler Fig | Gradually replace a legacy system with new services. |
| Anti-Corruption Layer | Prevent an external or legacy domain model from contaminating the internal domain model. |
| Database per Service | Each microservice owns and controls its persistence. |
| Eventual Consistency | Distributed data may temporarily differ before converging. |
| 12-Factor Config | Keep environment-specific configuration outside application code. |
| 12-Factor Processes | Keep application processes stateless and horizontally scalable. |
| 12-Factor Logs | Treat logs as event streams and let the environment aggregate them. |
| Observability | Understand system behavior using logs, metrics and distributed traces. |