A comprehensive guide to 107 modern software engineering patterns.
| ID | Design Pattern Name | Description | Type | Example |
|---|---|---|---|---|
| Distributed System & Microservices | ||||
| 1 | SAGA Pattern | The SAGA pattern is a failure management pattern for distributed transactions. It manages data consistency across mic... | Distributed | E-commerce Order Processing: Order Service -> Payment Service -> Shipping Service. If Shipping fails, the system executes compensating transactions to refund payment and cancel the order. |
| 2 | Two-Phase Commit (2PC) | Two-Phase Commit (2PC) is a standardized protocol that coordinates all the processes that participate in a distribute... | Distributed | Transferring funds between two different bank databases (Shards). Both shards must confirm they are ready to commit before the transaction is finalized. |
| 3 | Three-Phase Commit | Three-Phase Commit (3PC) is an atomic commitment protocol for distributed systems. It is an extension of the two-phas... | Distributed | A distributed database system where the coordinator might crash. 3PC ensures participants don't get stuck indefinitely holding locks. |
| 4 | Outbox Pattern | The Outbox pattern ensures that a database update and sending of a message to a message broker happen atomically. Ins... | Distributed | User Signup: The system inserts the User into the database and a 'WelcomeEmail' event into an 'Outbox' table in the same transaction. A background worker polls the table and sends the email. |
| 5 | Event Sourcing | Event Sourcing stores the state of a business entity as a sequence of state-changing events. Whenever the state of a ... | Distributed | A Bank Account. Instead of storing 'Balance: 100', we store [Deposited 50, Withdrew 10, Deposited 60]. The balance is calculated on the fly. |
| 6 | Idempotency Keys | An idempotency key is a unique token that identifies a request. If a client sends the same request with the same idem... | Distributed | Stripe API: If a timeout occurs during a charge request, the client retries with the same Idempotency-Key. Stripe checks the key and returns the original successful response instead of charging again. |
| 7 | Compensating Transactions | A compensating transaction is a transaction that undoes the effects of a series of steps that have already been commi... | Distributed | Booking a Flight and Hotel. If the Hotel booking fails, a Compensating Transaction is triggered to Cancel the Flight booking which was already committed. |
| 8 | Retries with Backoff | The Retry pattern enables an application to handle transient failures when it tries to connect to a service or networ... | Distributed | Calling an external Weather API. If it returns 503, wait 1s and retry. If fail, wait 2s, then 4s, then give up. |
| 9 | Circuit Breaker Pattern | The Circuit Breaker pattern prevents an application from repeatedly trying to execute an operation that's likely to f... | Distributed | If the 'Recommendation Service' is down, the 'Frontend' stops calling it (Circuit Open) and just shows popular products from a cache instead of hanging for 30 seconds. |
| 10 | Bulkhead Pattern | The Bulkhead pattern isolates elements of an application into pools so that if one fails, the others will continue to... | Distributed | A service has two thread pools: one for processing User Requests and one for Background Reports. If reports are slow and use up all threads, users can still log in. |
| 11 | Timeout Pattern | The Timeout pattern limits the amount of time an application waits for a response from a service. If the response is ... | Distributed | An HTTP client is configured with a 2-second timeout. If the server doesn't respond in 2 seconds, the client throws an error and frees up the connection. |
| 12 | Request/Response | This is the most common synchronous communication pattern where a client sends a request to a service and waits for a... | Communication | A browser sending an HTTP GET request to a web server for an HTML page. |
| 13 | Event-Driven Architecture (EDA) | A software architecture paradigm promoting the production, detection, consumption of, and reaction to events. Systems... | Communication | When a user updates their profile, a 'ProfileUpdated' event is emitted. The Search Service, Email Service, and Analytics Service all independently react to this event. |
| 14 | Publisher–Subscriber | A messaging pattern where senders of messages, called publishers, do not program the messages to be sent directly to ... | Communication | A YouTube channel uploads a video (Publish). Millions of subscribers get a notification (Subscribe). |
| 15 | Message Queues (MQ) | Message queues provide an asynchronous communications protocol, meaning that the sender and receiver of the message d... | Communication | An Image Upload service pushes a job to a RabbitMQ queue. A separate Worker service pulls the job and resizes the image. |
| 16 | API Gateway | An API Gateway is a server that acts as an API front-end, receiving API requests, enforcing throttling and security p... | Communication | Mobile App sends all requests to 'api.company.com'. The Gateway routes 'api/users' to User Service and 'api/orders' to Order Service. |
| 17 | Sidecar Pattern | Deploys components of an application into a separate process or container to provide isolation and encapsulation. Thi... | Communication | A Kubernetes Pod contains two containers: the Node.js API (Main) and Envopy Proxy (Sidecar). All network traffic flows through Envoy. |
| 18 | Ambassador Pattern | Creates a helper service that sends network requests on behalf of a client or consumer. It acts as an out-of-process ... | Communication | A legacy application needs to call a secure cloud API. An Ambassador proxy is installed on the localhost that handles the mTLS authentication, so the legacy app just calls localhost:8000. |
| 19 | Strangler Fig Pattern | A pattern for migrating a legacy system by gradually replacing specific functionalities with new applications and ser... | Communication | An old E-commerce monolith exists. You build a new 'Review Service'. The API Gateway routes '/reviews' to the new service, while everything else still goes to the Monolith. |
| 20 | CQRS | Command Query Responsibility Segregation (CQRS) is an architectural pattern that separates reading and writing into t... | Data | A social network details profile updates (Commands) to a Normalized SQL DB, while the Feed (Query) is read from a Denormalized NoSQL store for speed. |
| 21 | Database per Microservice | Each microservice's persistent data is private to that service and accessible only via its API. This ensures loose co... | Data | Order Service uses PostgreSQL. Catalog Service uses MongoDB. Recommendation Service uses Neo4j. They cannot access each other's DBs directly. |
| 22 | Shared Database Pattern | Multiple services access the same database. This is generally considered an anti-pattern in microservices but is comm... | Data | Order Service and Customer Service both read tables from the same Oracle instance. |
| 23 | Sharded Database Pattern | Database Sharding is a type of database partitioning that separates very large databases into smaller, faster, more e... | Data | A Global User Database is sharded by region: Users in US-East go to Shard A, Users in EU-West go to Shard B. |
| 24 | Materialized Views | A database object that contains the results of a query. It may be a local copy of data located remotely, or may be a ... | Data | Instead of joining 5 tables every time to show the 'Daily Sales Dashboard', a background job runs every hour and saves the result to a 'DailySales' table (view). |
| 25 | Read Replicas | Creating read-only copies of a database instance to scale out read-heavy workloads. | Data | A primary DB handles all INSERT/UPDATEs. Five Read Replicas handle all SELECT queries for the website. |
| 26 | Distributed Cache | A cache shared by multiple application servers, typically maintained as an external service. | Data | Redis or Memcached cluster used to store User Sessions and frequent Product Data, accessible by all instances of the web server. |
| 27 | Cache-Aside | The application code effectively maintains the cache. It attempts to read from cache; if miss, it reads from DB and w... | Data | App checks Redis for 'user:123'. If missing, fetches from MySQL, saves to Redis, and returns to user. |
| Event-Driven & Messaging | ||||
| 28 | Domain Events | A Domain Event captures the memory of something interesting which affects the domain. It is strictly part of the doma... | Event-Driven | When a user changes their address, a 'UserAddressChanged' event is created, not just a database update. This allows other systems to react. |
| 29 | Event Notification Pattern | A system notifies other systems that a change has occurred, but does not provide the full state. The receiver must ca... | Event-Driven | A webhook sends 'Order #123 Updated'. The receiver then calls GET /orders/123 to see what changed. |
| 30 | Event-Carried State Transfer | The event itself contains all the data the consumer needs. The consumer doesn't need to contact the producer for more... | Event-Driven | The 'OrderCreated' event includes the full item list, shipping address, and total amount. The Shipping Service can generate a label without calling the Order API. |
| 31 | Transactional Outbox Pattern | See 'Outbox Pattern' in Distributed Systems. Uses a local transaction to ensure event reliability. | Event-Driven | Writing the event to a SQL table in the same transaction as the business entity. |
| 32 | Polling Publisher | A polling process periodically queries the database for new events (like in an Outbox) and publishes them to a messag... | Event-Driven | A Cron job runs every 1 second: SELECT * FROM outbox WHERE sent=false; publish(); UPDATE set sent=true; |
| 33 | Competing Consumers | Multiple consumers pull messages from the same channel to share the workload. The system ensures only one consumer pr... | Event-Driven | 10 worker containers all listening to the 'ImageResize' queue. If 100 images are uploaded, the work is distributed across the 10 workers. |
| 34 | Message Routing / Filtering | The messaging system directs messages to specific queues based on content or metadata. | Event-Driven | A Topic Exchange routes log messages: 'error.*' goes to the Alert Queue, 'info.*' goes to the Audit Queue. |
| 35 | Fan-out / Fan-in | Fan-out broadcasts a message to multiple processors. Fan-in aggregates results from parallel executions. | Event-Driven | An Order is placed (Fan-out). Inventory, Email, and Fraud services process it in parallel. Once all 3 reply (Fan-in), the order is confirmed. |
| 36 | Dead Letter Queue (DLQ) | A service queue implementation to store messages that the messaging system cannot deliver to their destination or can... | Event-Driven | If a message fails to process 5 times, it is moved to the DLQ. DevOps can later inspect why it failed. |
| 37 | Poison Message Pattern | Handling a message that consistently causes a consumer to crash or fail. The solution is usually to detect this and m... | Event-Driven | A malformed JSON packet causes the parser to throw an unhandled exception. The consumer catches this, marks it 'Poison', and discards it. |
| GoF Patterns | ||||
| 38 | Singleton | Ensures a class has only one instance and provides a global point of access to it. Often used for shared resources. | Creational | A 'Logger' class where every part of the app writes to the same log file via the same instance. |
| 39 | Factory Method | Defines an interface for creating an object, but let subclasses decide which class to instantiate. It defers instanti... | Creational | A 'Logistics' class handles delivery. 'RoadLogistics' creates a 'Truck', 'SeaLogistics' creates a 'Ship'. The client just calls 'createTransport()'. |
| 40 | Abstract Factory | Provides an interface for creating families of related or dependent objects without specifying their concrete classes. | Creational | A UI Factory creates Buttons and Checkboxes. The 'MacFactory' creates MacButton and MacCheckbox. The 'WinFactory' creates WinButton and WinCheckbox. |
| 41 | Builder | Separates the construction of a complex object from its representation so that the same construction process can crea... | Creational | A 'HouseBuilder'. You can call .setWalls(4), .setRoof('Shingle'), .addGarage().build(). You can use the same builder to make a different house. |
| 42 | Prototype | Creates new objects by copying an existing object, known as the prototype. | Creational | In a game, spawning 1000 'Goblin' enemies. Instead of running the initialization code 1000 times, you create one Goblin and clone it 999 times. |
| 43 | Adapter | Allows objects with incompatible interfaces to collaborate. It acts as a wrapper. | Structural | You have a 'StockData' XML service, but your analytics library needs JSON. You write an XMLtoJSONAdapter class. |
| 44 | Bridge | Splits a large class or a set of closely related classes into two separate hierarchies—abstraction and implementation... | Structural | A 'RemoteControl' (Abstraction) works with a 'TV' (Implementation). You can add new Remotes or new TVs without breaking each other. |
| 45 | Composite | Lets you compose objects into tree structures and then work with these structures as if they were individual objects. | Structural | A 'Folder' contains 'Files' and other 'Folders'. You can call 'getSize()' on a Folder, and it recursively calculates the size of everything inside. |
| 46 | Decorator | Lets you attach new behaviors to objects by placing these objects inside special wrapper objects that contain the beh... | Structural | A 'Coffee' object. You wrap it in 'MilkDecorator', then 'SugarDecorator'. The cost() method adds up existing cost + milk + sugar. |
| 47 | Facade | Provides a simplified interface to a library, a framework, or any other complex set of classes. | Structural | A 'SmartHome' facade has a method 'movieMode()'. Internally, it dims lights, turns on TV, closes blinds, and sets volume. |
| 48 | Flyweight | Lets you fit more objects into the available amount of RAM by sharing common parts of state between multiple objects ... | Structural | A Text Editor. Instead of storing font data for every letter 'A', it stores one 'Font object' for 'A' and 1000 pointers to it. |
| 49 | Proxy | Lets you provide a substitute or placeholder for another object. A proxy controls access to the original object. | Structural | A website displays a low-res placeholder image while the high-res image downloads in the background. |
| 50 | Chain of Responsibility | Lets you pass requests along a chain of handlers. Upon receiving a request, each handler decides either to process th... | Behavioral | Web Server Middleware: Authentication -> Logging -> Compression -> Router. Each step passes control to the next. |
| 51 | Command | Turns a request into a stand-alone object that contains all information about the request. | Behavioral | A text editor. 'Copy', 'Paste', 'Type' are all Command objects. You can put them in a stack to Undo them. |
| 52 | Interpreter | Given a language, defines a representation for its grammar along with an interpreter that uses the representation to ... | Behavioral | An app that calculates '5 + 10 * 2'. It parses the string into an expression tree and evaluates it. |
| 53 | Iterator | Lets you traverse elements of a collection without exposing its underlying representation (list, stack, tree, etc.). | Behavioral | The 'foreach' loop in most languages. It works on Arrays, Lists, and Trees identically. |
| 54 | Mediator | Lets you reduce chaotic dependencies between objects. The pattern restricts direct communications between the objects... | Behavioral | Air Traffic Control. Planes don't talk to each other; they talk to the Tower, which coordinates them. |
| 55 | Memento | Lets you save and restore the previous state of an object without revealing the details of its implementation. | Behavioral | A text editor saves a snapshot of the document state before every change. |
| 56 | Observer | Lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they'r... | Behavioral | A Spreadsheet. If you change value in Cell A1, the Chart observing A1 automatically updates. |
| 57 | State | Lets an object alter its behavior when its internal state changes. It appears as if the object changed its class. | Behavioral | A Phone. If 'Unlocked', pressing buttons calls numbers. If 'Locked', pressing buttons turns on the screen. |
| 58 | Strategy | Lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable. | Behavioral | A GPS App. You can switch routing strategy: 'Walking', 'Driving', or 'Public Transport'. The map logic remains the same. |
| 59 | Template Method | Defines the skeleton of an algorithm in the superclass but lets subclasses override specific steps of the algorithm w... | Behavioral | A Data Miner. Steps: openFile() -> extractData() -> userMethod() -> closeFile(). Subclasses only implement extractData(). |
| 60 | Visitor | Lets you separate algorithms from the objects on which they operate. | Behavioral | You have a graph of shapes. You write an 'XMLExportVisitor' that walks the graph and generates XML, without modifying the shape classes. |
| Architectural Patterns | ||||
| 61 | Monolithic Architecture | A single tiered software application in which the user interface and data access code are combined into a single prog... | Architecture | A standard Ruby on Rails or Django app where everything is in one repo and deployed as one unit. |
| 62 | Layered Architecture | Organizes the system into horizontal layers, where each layer has a specific role (Presentation, Business, Persistenc... | Architecture | Presentation Layer -> Service Layer -> DAO Layer -> Database. |
| 63 | Hexagonal Architecture | Also known as Ports and Adapters. It allows an application to easier be tested in isolation from external devices lik... | Architecture | The Core logic is in the center. Database adapters and REST adapters plug into the Core. |
| 64 | Clean Architecture | A philosophy that separates the elements of a design into ring levels. The most important rule is that dependencies c... | Architecture | Entities (Center) -> Use Cases -> Adapters -> Frameworks (Outside). |
| 65 | Onion Architecture | Similar to Hexagonal/Clean. It relies on the Dependency Inversion Principle. The application core needs no dependenci... | Architecture | Core Domain -> Domain Services -> Application Services -> UI/Infra. |
| 66 | Microservices Architecture | An architectural style that structures an application as a collection of services that are highly maintainable, testa... | Architecture | Netflix: hundreds of small services talking to each other. |
| 67 | Serverless Architecture | A way to build and run applications and services without having to manage infrastructure. Your application is split i... | Architecture | AWS Lambda functions triggering on S3 uploads or API Gateway calls. |
| 68 | Service-Oriented Architecture (SOA) | A style where services are provided to the other components by application components, through a communication protoc... | Architecture | An Enterprise Service Bus (ESB) connecting a Billing System (Mainframe) to a Web Portal. |
| 69 | Headless Architecture | Decoupling the frontend (head) from the backend (body). The backend just serves data via API. | Architecture | Contentful (Headless CMS) serving content to a Website, a Mobile App, and a Smart Watch. |
| 70 | MVC | Model-View-Controller. Separates internal representation of information from the way information is presented to and ... | UI Arch | Spring MVC, Ruby on Rails. |
| 71 | MVVM | Model-View-ViewModel. Facilitates a separation of development of the graphical user interface. | UI Arch | React (View) + State (ViewModel). |
| 72 | MVP | Model-View-Presenter. Derivation of MVC, mostly used for building user interfaces. | UI Arch | Windows Forms applications. |
| 73 | Flux | Application architecture for building client-side web applications. It utilizes a unidirectional data flow. | UI Arch | Redux or Vuex state management. |
| 74 | Redux | A predictable state container for JavaScript apps. | UI Arch | Global Store with Actions and Reducers. |
| 75 | Observer-Based UI | UI updates automatically when underlying data changes. | UI Arch | RxJS Observables binding data to UI components. |
| Cloud & Deployment | ||||
| 76 | Blue–Green Deployment | A technique that reduces downtime and risk by running two identical production environments called Blue and Green. | Deployment | Router points to Blue (v1). Deploy v2 to Green. Switch router to Green. |
| 77 | Canary Deployment | A pattern to roll out new features to only a small subset of users before rolling it out to the entire infrastructure. | Deployment | Route 5% of traffic to v2 pods. If no errors, increase to 100%. |
| 78 | Rolling Updates | Updating instances one by one or in batches, rather than all at once. | Deployment | Kubernetes Rolling Update: Replace Pod 1, then Pod 2, etc. |
| 79 | Immutable Infrastructure | Servers are never modified after they're deployed. If something needs to be updated, you replace the entire server/co... | Deployment | Docker containers. You don't patch a running container; you build a new image and deploy it. |
| 80 | Infrastructure as Code | Managing and provisioning computer data centers through machine-readable definition files, rather than physical hardw... | Deployment | Terraform scripts defining the AWS VPC and EC2 instances. |
| 81 | Circuit Breaker | See 'Circuit Breaker' in Distributed Systems. Prevents cascading failures. | Reliability | Hystrix. |
| 82 | Retry Pattern | See 'Retries with Backoff' in Distributed Systems. Handling transient failures. | Reliability | HTTP Retries. |
| 83 | Fail-Fast | A system that immediately reports at its interface any condition that is likely to indicate a failure. | Reliability | Checking for null arguments at the start of a function. |
| 84 | Fallback Pattern | Providing a backup plan or default value when a service fails. | Reliability | If the movie poster service is down, show a generic placeholder image. |
| 85 | Graceful Degradation | The ability of a computer, machine, electronic system or network to maintain limited functionality even when a large ... | Reliability | If the search index is down, show 'Recent Items' list instead of a 500 error. |
| 86 | Rate Limiting | Controlling the rate of traffic sent or received by a network interface controller. | Reliability | Allowing only 100 req/min per IP address. |
| 87 | Bulkhead Pattern | See 'Bulkhead' in Distributed Systems. Isolating resources. | Reliability | Thread pools. |
| 88 | Sidecar | See 'Sidecar' in Communication. Helper container. | Container | Envoy. |
| 89 | Ambassador | See 'Ambassador' in Communication. Proxy for client. | Container | Proxy sidecar. |
| 90 | Adapter | See 'Adapter' in GoF. Structural pattern adaptation. | Container | Legacy wrapper. |
| 91 | Service Mesh | A dedicated infrastructure layer for facilitating service-to-service communications between microservices, often usin... | Container | Istio managing mTLS and tracing between services. |
| High Availability & Scaling | ||||
| 92 | Horizontal Scaling | Adding more machines to a resource pool (also known as scaling out). | Scaling | Adding more EC2 instances to an Auto Scaling Group. |
| 93 | Vertical Scaling | Adding more power (CPU, RAM) to an existing machine (also known as scaling up). | Scaling | Upgrading an AWS RDS instance from t3.micro to m5.large. |
| 94 | Sharding | A method of splitting and storing a single logical dataset in multiple databases. | Scaling | Splitting a User table into 10 servers based on UserID. |
| 95 | Partitioning | Dividing a logical design into several distinct physical units. | Scaling | Functional partitioning: putting Inventory and Orders on different servers. |
| 96 | Leader–Follower | Ideally suited for read-heavy workloads. One node (Leader) handles writes, others (Followers) replicate data and hand... | Scaling | Primary DB accepts writes, replicas serve read traffic. |
| 97 | Active–Active | A cluster of at least two nodes running the same kind of service simultaneously. | Scaling | Two Load Balancers in different zones serving traffic at the same time. |
| 98 | Active–Passive | One node is active, others are on standby waiting for a failure to take over. | Scaling | Primary server runs. Secondary server is off/idle until Primary fails. |
| 99 | Distributed Cache | See 'Distributed Cache' in Data Patterns. | Scaling | Redis. |
| Security Patterns | ||||
| 100 | Zero Trust Architecture | A security concept centered on the belief that organizations should not automatically trust anything inside or outsid... | Security | Google BeyondCorp. Every request must be authenticated and authorized. |
| 101 | Defense in Depth | A layering tactic, conceived by the NSA as a comprehensive approach to information and electronic security. | Security | Firewall -> WAF -> App Auth -> Database Encryption. |
| 102 | JWT Authentication | JSON Web Token is an open standard that defines a compact and self-contained way for securely transmitting informatio... | Security | User logs in, gets a JWT. Sends JWT with every request. Server validates signature. |
| 103 | Token Bucket | An algorithm used in packet switched computer networks and telecommunications networks to check that data transmissio... | Security | API Gateway gives each user a bucket of 10 tokens. Each request takes 1. |
| 104 | RBAC | Role-based access control is a method of restricting network access based on the roles of individual users within an ... | Security | Admin role has all permissions. Viewer role can only generic GET requests. |
| 105 | OAuth 2.0 | OAuth 2.0 is the industry-standard protocol for authorization. | Security | Allowing a third-party print service to access your photos on Google Photos without giving them your password. |
| 106 | API Key | A code passed in by computer programs calling an application programming interface (API) to identify the calling prog... | Security | Google Maps API keys. |
| 107 | Certificate Pinning | Associating a host with their expected X.509 certificate or public key. | Security | App contains the hash of the backend's SSL cert and rejects any other certs. |