Skip to content
StackPractices

Patterns

Software design and architecture patterns explained with real, runnable examples.

203 results

advanced

Agent Tool Selection Pattern

Dynamically select which tools an LLM agent can use based on the task context. Reduce token usage and improve decision quality by narrowing the tool set.

intermediate

Embedding Cache Pattern

Cache LLM embeddings to reduce API calls and cost. Store embeddings with a content hash key and serve from cache on repeated inputs.

intermediate

Human-in-the-Loop Pattern

Pause LLM agent execution for human approval before high-impact actions. Route decisions to a reviewer when confidence is low or stakes are high.

intermediate

LLM Fallback Pattern

Fall back to alternative LLM providers or models when the primary fails. Handle rate limits, timeouts, and errors gracefully with a provider chain.

intermediate

LLM Guardrails Pattern

Validate LLM inputs and outputs with rules, classifiers, and content filters. Prevent prompt injection, toxic content, and data leakage before reaching users.

intermediate

LLM Router Pattern

Route queries to different LLM models based on complexity, cost, and latency requirements. Classify input before dispatching to the right model.

intermediate

Prompt Chaining Pattern

Chain multiple LLM calls where each step's output feeds the next step's input. Break complex tasks into smaller, verifiable prompts for better results.

intermediate

RAG Hybrid Search Pattern

Combine keyword (BM25) and semantic (vector) search to improve retrieval accuracy in RAG pipelines. Fuse ranked results using reciprocal rank fusion.

intermediate

Ambassador: Offload Cross-Cutting Concerns to a Proxy

How to offload cross-cutting concerns to a proxy ambassador. Covers connection pooling, retry logic, circuit breaking, monitoring, and TLS termination for client services.

advanced

Anti-Corruption Layer: Isolate Legacy with Adapters

How to isolate legacy systems with translation adapters. Covers ACL facade, domain translation, bidirectional mapping, and gradual legacy replacement.

intermediate

Backends for Frontends: Dedicated Backend per Client Type

How to create dedicated backends per client type. Covers BFF for web, mobile, and desktop. Covers API aggregation, client-specific optimization, and GraphQL BFF.

intermediate

Compute Resource Consolidation Pattern

Combine workloads into fewer compute resources to reduce cost, improve utilization, and simplify operations.

intermediate

External Configuration Store Pattern

Centralize application configuration outside of deployment artifacts to support live updates and multi-environment management.

intermediate

Gateway Routing Pattern

Route requests to multiple backend services through a single entry point that handles cross-cutting concerns.

beginner

Health Endpoint Monitoring Pattern

Expose lightweight health endpoints so orchestrators, load balancers, and monitoring tools can verify service availability.

intermediate

Leader Election Pattern

Coordinate a single active instance among multiple distributed nodes to avoid conflicts and split-brain scenarios.

intermediate

Modular Monolith: Single Deployable with Module Boundaries

How to build a modular monolith with strict internal module boundaries. Covers module isolation, shared kernel, inter-module communication, and migration to microservices.

advanced

Multi-Tenant Data Isolation Pattern

Isolate tenant data in shared infrastructure using row-level security, schema-per-tenant, or database-per-tenant strategies. A pattern for SaaS applications.

intermediate

Pipes and Filters Pattern

Chain processing steps with independent filters connected by pipes. A pattern for data transformation pipelines where each step is reusable and composable.

intermediate

Sidecar Pattern: Extend Services with Companion Containers

How to extend services with companion containers for cross-cutting concerns. Covers sidecar containers, shared volumes, health probes, and service mesh sidecars.

intermediate

Strangler Fig: Gradually Replace Legacy by Intercepting

How to gradually replace a legacy system by intercepting routes and routing traffic to new services. Covers strangler fig, incremental migration, and cutover.

advanced

Federated Identity Pattern

Delegate authentication to external identity providers. A pattern for integrating OAuth2, OIDC, SAML, and SSO across multiple services and organizations.

advanced

Voucher Pattern

Validate claims and delegate access using signed vouchers without exposing sensitive data. A security pattern for token-based authorization between services.

advanced

Batch-to-Streaming Bridge

How to bridge batch and streaming pipelines with a data lake. Covers Lambda architecture, Kafka Connect S3 sink, schema alignment, and unified serving layer.

advanced

CDC Pattern: Stream Database Changes to Downstream

How to stream database changes to downstream consumers with CDC. Covers log-based CDC, Debezium, Kafka Connect, outbox pattern, and consumer reconciliation.

advanced

Data Lineage Tracking: Track Origin End-to-End

How to track data origin and transformations end-to-end. Covers column-level lineage, OpenLineage, Marquez, metadata injection, and impact analysis.

intermediate

ETL Extract-Transform-Load

How to build ETL pipelines with extract, transform, and load stages. Covers staging tables, incremental extraction, idempotent loads, and orchestration.

intermediate

Idempotent Load: Re-run Data Loads Safely Without Duplicates

How to re-run data loads safely without duplicates. Covers deduplication keys, MERGE upserts, load IDs, partition overwrite, and transactional loads.

advanced

Schema Registry Evolution

How to manage schema versions for streaming pipelines with a schema registry. Covers Avro, backward compatibility, forward compatibility, and consumer migration.

intermediate

Abstract Factory for Cross-Platform UI Component Families

Create families of related objects without specifying concrete classes, enabling platform-specific implementations that share a common interface

intermediate

Abstract Factory Pattern

Create families of related objects without specifying concrete classes. A creational design pattern for consistent object families.

beginner

Active Record Pattern

Wrap a database table or view in a class where an instance is tied to a single row, and the class provides methods for CRUD operations directly on the object.

advanced

Actor Model Pattern

Isolate state in actors that communicate only via messages. Each actor processes one message at a time, eliminating shared-state concurrency bugs by design.

beginner

Adapter Pattern

Convert the interface of a class into another interface clients expect. A structural design pattern for interface compatibility.

beginner

Adapter Pattern for Integrating External REST APIs

Use the Adapter pattern to normalize responses from external REST APIs into a consistent internal model without leaking third-party formats into your domain

advanced

Aggregate Pattern

Encapsulate a cluster of domain objects treated as a single unit for data changes. An Aggregate Root controls access to its internal entities and value objects.

intermediate

Ambassador Pattern for Resilient Remote Service Access

Add a local ambassador that handles retries, circuit breaking, and monitoring when calling remote services, keeping the client simple and the service logic pure

intermediate

Async Generator Pattern

Stream data lazily with async generators. Yield values one at a time as they become available, enabling memory-efficient processing of large or infinite data sequences.

intermediate

Back-Pressure Pattern

Prevent upstream systems from overwhelming downstream consumers by propagating flow-control signals backward through the pipeline, ensuring stable throughput under load.

intermediate

Backend for Frontend (BFF) Pattern

Create dedicated backend services tailored to the specific needs of each frontend client type, aggregating downstream APIs and optimizing data shapes per platform.

advanced

Blackboard Pattern

A shared knowledge space where independent specialized modules collaborate to solve complex problems by contributing partial solutions.

intermediate

Blue-Green Deployment Pattern

Run two identical environments and switch traffic between them. Deploy to the idle environment, test it, then flip the router for instant release or rollback.

intermediate

Bridge Pattern

Decouple an abstraction from its implementation so both can vary independently. A structural design pattern for platform independence.

intermediate

Bridge Pattern for Decoupling UI Components from Themes

Separate an abstraction from its implementation so both can vary independently using the Bridge pattern for pluggable UI themes and rendering engines

intermediate

Builder Pattern

Construct complex objects step by step. A creational design pattern for readable, configurable object construction.

beginner

Builder Pattern for Complex Configuration Objects

Use the Builder pattern to construct complex configuration objects with optional parameters and sensible defaults without telescoping constructors

intermediate

Business Delegate Pattern

Reduce coupling between presentation and business tiers by introducing an intermediary that handles lookup, creation, and invocation of business services.

beginner

Cache-Aside Pattern

Load data into the cache on demand from the backing store. A caching pattern that gives the application full control over what and when to cache.

intermediate

Cache Invalidation Pattern

Strategies for keeping cached data fresh: TTL expiration, explicit invalidation, write-through, and event-driven cache eviction.

advanced

Cache Stampede Prevention Pattern

Prevent thundering herd cache misses with locks, single-flight, and early refresh strategies to protect the database from concurrent reloads.

intermediate

Canary Release Pattern

Route a small percentage of traffic to the new version while the rest stays on stable. Monitor health metrics and gradually increase or roll back based on results.

intermediate

Chain of Responsibility for Request Processing Middleware

Pass requests along a chain of handlers where each handler decides whether to process the request or pass it to the next handler in the pipeline

intermediate

Chain of Responsibility Pattern

Pass requests along a chain of handlers until one handles it. A behavioral design pattern for decoupling senders and receivers.

intermediate

Circuit Breaker Pattern

Prevent cascading failures by stopping requests to failing services. An architectural pattern for resilient distributed systems.

intermediate

Claim Check Pattern

Store large payloads in external storage and pass only a lightweight reference token through the message bus, reducing broker load and preventing message size limits from being exceeded.

intermediate

Command Pattern

Encapsulate a request as an object, letting you parameterize clients with queues, logs, and undoable operations. A behavioral design pattern.

intermediate

Command Pattern with Undo/Redo in TypeScript

Implement the Command pattern to encapsulate requests as objects, enabling undo/redo operations, request queuing, and operation logging

advanced

Compensating Transaction Pattern

Undo the effects of a completed transaction by executing a counter-operation, enabling eventual consistency in long-running business processes across distributed services.

intermediate

Composite Entity Pattern

Map a coarse-grained entity to multiple database tables by composing dependent objects, reducing the number of fine-grained remote calls in EJB and distributed systems.

intermediate

Composite Pattern

Compose objects into tree structures to represent part-whole hierarchies. A structural design pattern for treating individual objects and compositions uniformly.

intermediate

Composite Pattern for UI Component Trees in React

Use the Composite pattern to compose objects into tree structures, letting clients treat individual objects and compositions uniformly in UI component hierarchies

beginner

Content Delivery Network (CDN) Pattern

Distribute static and live content through geographically dispersed edge servers to reduce latency, improve availability, and offload origin infrastructure.

intermediate

Context Object Pattern

Encapsulate state and services needed by multiple components into a single context object, reducing method signature bloat and decoupling code from specific environment details.

advanced

CQRS Pattern

Separate read and write operations into different models, optimizing each for their specific workload. A data pattern for scalable systems.

beginner

Data Access Object (DAO) Pattern

Abstract and encapsulate all access to a data source by exposing a clean interface while hiding persistence details from business logic.

intermediate

Data Mapper Pattern

Separate in-memory domain objects from the database by delegating persistence to a dedicated mapper layer, keeping models framework-agnostic.

intermediate

Database per Service Pattern

Give each microservice its own private database to ensure loose coupling, independent deployment, and technology heterogeneity across the application portfolio.

intermediate

Dead Letter Channel Pattern

Route unprocessable messages to a separate dead letter queue for inspection and replay. Prevent poison messages from blocking the main queue indefinitely.

intermediate

Decorator Pattern

Add new functionality to objects dynamically by wrapping them. A structural design pattern for flexible behavior extension.

intermediate

Decorator Pattern for HTTP Request Pipelines

Use the Decorator pattern to compose cross-cutting concerns like logging, metrics, and retries into HTTP request pipelines without modifying core logic

intermediate

Dependency Injection Pattern

Supply dependencies from outside rather than creating them internally. An architectural pattern for decoupled, testable code.

intermediate

Dependency Injection Container in TypeScript

Build a lightweight DI container that resolves class dependencies automatically, enabling testable, loosely-coupled applications without frameworks like Angular or InversifyJS

intermediate

Deployment Ring Pattern

Roll out changes progressively in rings of increasing size. Start with a small group, verify health, then expand to larger rings before full deployment.

intermediate

Distributed Lock Pattern

Coordinate mutually exclusive access to shared resources across distributed nodes using a consensus-based lock service, preventing race conditions in scaled-out systems.

intermediate

Domain Event Pattern

Capture and publish major occurrences within a domain model to decouple side effects from core business logic and enable reactive workflows.

intermediate

Eager Loading Pattern

Load related data in a single query rather than multiple round-trips, preventing the N+1 problem and improving read performance.

advanced

Entity-Component-System (ECS) Pattern

Compose entities from pure data components and process them with systems, enabling high-performance and flexible game object architecture without deep inheritance.

intermediate

Event Bus Pattern

Decouple components by routing events through a central bus. A behavioral pattern for loosely coupled communication between modules.

intermediate

Event-Carried State Transfer Pattern

Replicate state changes across services by publishing events that carry the full updated entity state, enabling consumers to maintain their own local copies without querying the source.

advanced

Event Sourcing Pattern

Store the state of an application as a sequence of events rather than storing only the current state. An architectural pattern for audit-friendly systems.

beginner

Facade Pattern

Provide a simplified interface to a complex subsystem. A structural pattern that hides implementation details behind a clean API.

beginner

Factory Pattern

Create objects without specifying the exact class to instantiate. A creational design pattern for flexible object creation.

intermediate

Flyweight Pattern

Share objects to support large numbers of fine-grained objects efficiently. A structural design pattern for memory optimization.

intermediate

Flyweight Pattern for Efficient Large-Scale Object Sharing

Use the Flyweight pattern to minimize memory usage by sharing as much data as possible between similar objects, essential for rendering large datasets

intermediate

Front Controller Pattern

Route all incoming requests through a single handler that dispatches to the appropriate page command, centralizing request processing and security.

intermediate

Gatekeeper Pattern

Place a validation and security boundary at the edge of a system to inspect, sanitize, and authenticate all incoming requests before they reach internal services.

advanced

Geode Pattern

Distribute data across nodes with partitioning so each node owns a shard. Horizontal scaling without shared state, with locality and fault isolation per partition.

intermediate

Graceful Degradation Pattern

Degrade functionality instead of failing when dependencies are unavailable. Serve partial results, cached data, or fallback features to keep users running.

intermediate

Idempotent Consumer Pattern

Process messages from a queue exactly once regardless of duplicates by using idempotent operations, unique identifiers, and deduplication strategies at the consumer level.

intermediate

Identity Map Pattern

Ensure each object is loaded only once per transaction by caching instances by their primary key, preventing duplicate in-memory representations of the same database row.

intermediate

Inbox Pattern

Use a dedicated inbox table or queue to record incoming events or requests, ensuring reliable delivery, deduplication, and idempotent processing even when downstream systems fail.

intermediate

Intercepting Filter Pattern

Compose cross-cutting concerns into a chain of pluggable filters that intercept requests and responses, enabling reusable preprocessing and postprocessing logic.

advanced

Interpreter Pattern

Define a representation for a language's grammar along with an interpreter that uses the representation to interpret sentences. A behavioral design pattern for mini-languages.

advanced

Interpreter Pattern for Domain-Specific Expression Languages

Build a language interpreter that evaluates expressions and rules by representing grammar as composable objects, useful for formulas, queries, and business rules

beginner

Iterator Pattern

Provide a way to access elements of a collection sequentially without exposing its underlying representation. A behavioral design pattern for traversal.

intermediate

Iterator Pattern for Custom Collection Traversal in

Provide a way to access elements of an aggregate object sequentially without exposing its underlying representation using the Iterator pattern

advanced

Lock-Free Queue Pattern

Build high-throughput queues using atomic operations instead of locks. Multiple threads can enqueue and dequeue concurrently without blocking or context-switching overhead.

beginner

Manager Pattern

Encapsulate lifecycle, coordination, and access control for a set of related objects through a dedicated manager class that centralizes operations and enforces invariants.

beginner

Marker Interface Pattern

Use empty interfaces as metadata tags to signal properties or capabilities at compile time and runtime, enabling type-safe checks without modifying class behavior.

intermediate

Materialized View Pattern

Precompute and store expensive query results in a read-optimized cache to avoid repeated costly aggregation or joins across large datasets.

intermediate

Mediator Pattern

Define an object that encapsulates how a set of objects interact. A behavioral design pattern for reducing chaotic dependencies.

intermediate

Mediator Pattern for Loose Component Coupling in

Reduce chaotic dependencies between UI components by introducing a mediator that centralizes communication, preventing explicit references between peers

intermediate

Memento Pattern

Capture and restore an object's internal state without violating encapsulation. A behavioral design pattern for undo/redo.

intermediate

Memento Pattern for State Snapshot and Restoration

Capture and externalize an object's internal state without violating encapsulation, enabling undo, serialization, and state rollback in applications

intermediate

Message Deduplication Pattern

Prevent duplicate processing by tracking message IDs with idempotency keys. Consumers check a store before processing to skip messages already handled.

intermediate

Message Deferral Pattern

Delay message processing to a scheduled time. Move messages that cannot be processed now to a deferred queue or schedule them for later delivery.

intermediate

Message Queue Load Leveling Pattern

Smooth traffic spikes by placing a queue between a producer and a consumer. The producer writes messages at any rate; the consumer processes them at a steady pace.

beginner

Mixin Pattern

Add reusable behavior to classes without inheritance by composing methods from shared objects into a target class.

intermediate

Model-View-Presenter (MVP) Pattern

Separate presentation logic from the view by introducing a presenter that intermediates between the model and a passive view, enabling testable UI code.

intermediate

Model-View-ViewModel (MVVM) Pattern

Bind UI components declaratively to a ViewModel that exposes data and commands, enabling automatic synchronization between view and state.

beginner

Module Pattern

Encapsulate private state and behavior inside a self-contained unit with a public API. A structural pattern for organizing code into reusable, scope-safe modules.

intermediate

Multiton Pattern

Manage a map of named singleton instances, providing controlled access to a finite set of shared objects identified by keys.

intermediate

MVC Pattern

Separate application into Model, View, and Controller components. An architectural design pattern for organized, maintainable code.

beginner

MVC Pattern in Modern Frontend Applications

Apply the Model-View-Controller pattern to React and Vue applications to separate data, UI, and interaction logic for maintainable component architecture

beginner

Null Object Pattern

Use a default object instead of null references to eliminate null checks and simplify client code. A behavioral pattern for safer defaults.

intermediate

Object Pool Pattern

Reuse expensive objects instead of creating and destroying them repeatedly. A creational pattern for managing scarce resources efficiently.

beginner

Observer Pattern

Define a subscription mechanism to notify multiple objects about events. A behavioral design pattern for event-driven communication.

advanced

Outbox Pattern

Reliably publish domain events by persisting them in an outbox table within the same database transaction as the business operation.

beginner

Page Controller Pattern

Use a dedicated controller object for each logical page in a web application, handling the request and populating the view for that specific page.

beginner

Partial Class Pattern

Split a single class definition across multiple source files to separate auto-generated code from hand-written code, or to organize large classes by concern.

intermediate

Plugin Pattern

Enable third-party extensions by defining extension points in a host system that loads and executes live external modules.

intermediate

Priority Queue Pattern

Process tasks based on priority rather than arrival order, ensuring high-priority work gets resources before lower-priority tasks even if it arrived later.

intermediate

Producer-Consumer Pattern

Decouple production and consumption with a shared queue. Producers generate items at their own pace; consumers process them independently through a bounded or unbounded buffer.

intermediate

Prototype Pattern

Create new objects by copying existing ones. A creational design pattern for cloning and object duplication.

intermediate

Prototype Pattern for Object Cloning and Configuration

Create new objects by copying existing ones, allowing pre-configured templates and avoiding subclass explosion when object creation is expensive

intermediate

Proxy Pattern

Provide a surrogate or placeholder for another object to control access to it. A structural design pattern for access control, lazy loading, and logging.

intermediate

Proxy Pattern for API Response Caching

How to implement a caching proxy that intercepts API calls and stores responses to reduce latency and avoid redundant network requests

intermediate

Publish-Subscribe Pattern

Broadcast events to multiple independent subscribers. Publishers send messages to a topic without knowing which subscribers exist, enabling loose coupling between producers and consumers.

intermediate

Queue-Based Load Leveling Pattern

Introduce a queue between task producers and consumers to smooth out traffic spikes, decouple components, and prevent downstream services from being overwhelmed by burst workloads.

advanced

Reactive Streams Pattern

Process asynchronous data streams with backpressure. Subscribers request N items at a time, preventing fast producers from overwhelming slow consumers.

intermediate

Read-Through Cache Pattern

A transparent cache layer that intercepts read requests, fetches from the data source on miss, and populates the cache automatically.

advanced

Refresh-Ahead Cache Pattern

Proactively refresh cache entries before they expire to eliminate cache misses on hot keys and maintain consistent read latency.

intermediate

Registry Pattern

Centralize access to shared services and objects via a lookup table. A structural pattern that decouples consumers from concrete implementations.

intermediate

Repository Pattern

Abstract data access logic behind a clean interface. An architectural design pattern for testable, maintainable data layers.

intermediate

Repository Pattern with TypeScript Generics

Implement a type-safe repository pattern in TypeScript that decouples data access logic from domain services using generics and interfaces

intermediate

Retry Pattern

Retry an operation that has failed with transient errors, using configurable strategies like fixed delay, exponential backoff, or circuit breaker integration.

intermediate

Role Pattern

Assign dynamic roles to objects at runtime instead of hard-coding behavior in class hierarchies, enabling flexible identity changes without inheritance bloat.

advanced

Saga Pattern

Manage distributed transactions across multiple services by chaining local transactions with compensating actions for rollbacks. A microservices pattern.

advanced

Scheduler Agent Supervisor Pattern

Coordinate resilient job scheduling by separating scheduling logic from execution agents and adding a supervisor that monitors, restarts, and manages agent lifecycle.

intermediate

Sequential Convoy Pattern

Preserve message ordering for related messages in a distributed system by grouping them into ordered sequences and processing them one at a time through a single consumer.

intermediate

Serverless DB Connection Pooling Pattern

Manage database connections across serverless invocations by using external connection poolers, connection reuse, and lightweight clients to avoid connection exhaustion.

advanced

Serverless Event Sourcing Pattern

Store function state as an append-only event log so workflows can be replayed, audited, and recovered without a persistent database.

intermediate

Serverless Fanout Pattern

Broadcast a single event to multiple independent consumers via SNS, EventBridge, or SQS so each consumer processes the event without coupling.

advanced

Serverless Function Composition Pattern

Chain serverless functions via Step Functions or orchestration layers to build multi-step workflows with retries, branching, and state management.

advanced

Serverless Throttling Pattern

Handle backpressure in serverless by using SQS, token buckets, and concurrency limits to protect downstream services from burst traffic.

intermediate

Serverless Warm Pool Pattern

Keep Lambda functions warm by sending periodic ping events to reduce cold start latency for latency-sensitive workloads.

advanced

Sharding Pattern

Split a large dataset into smaller partitions (shards) distributed across multiple servers to improve growth, performance, and availability beyond single-node limits.

intermediate

Shed Load Pattern

Drop requests proactively under extreme load to protect the system. Reject excess traffic before it consumes resources and causes cascading failures.

beginner

Singleton Pattern

Ensure a class has only one instance and provide global access to it. A creational design pattern for controlled object creation.

intermediate

SOLID Principles in TypeScript with Practical Examples

Apply the five SOLID principles to TypeScript code to improve maintainability, testability, and reduce coupling in object-oriented designs

intermediate

Specification Pattern

Encapsulate business rules for selecting objects as reusable, composable predicate objects that can be combined with logical operators.

intermediate

State Pattern

Allow an object to alter its behavior when its internal state changes. A behavioral design pattern for finite state machines.

beginner

Static Content Hosting Pattern

Deploy static files to a dedicated content delivery network or object storage to offload origin servers, reduce latency, and improve availability for assets like images, CSS, and JavaScript.

beginner

Strategy Pattern

Define a family of algorithms, encapsulate each one, and make them interchangeable. A behavioral design pattern for flexible behavior selection.

beginner

Template Method Pattern

Define the skeleton of an algorithm in a base class, letting subclasses override specific steps without changing the algorithm's structure. A behavioral design pattern.

intermediate

Thread Pool Pattern

Reuse a fixed set of threads for short-lived tasks instead of creating a new thread per task. Reduces overhead and bounds resource usage under load.

intermediate

Throttling Pattern

Limit the rate at which a system processes requests or consumes resources to prevent overload, ensure fair usage, and maintain predictable performance under varying load.

beginner

Timeout Pattern

Prevent operations from hanging indefinitely by enforcing a maximum execution time. A resilience pattern for predictable response times.

intermediate

Twin Pattern

Provide an alternative to multiple inheritance by linking two separate classes through mutual references, allowing them to delegate methods to each other as needed.

advanced

Two-Level Cache Pattern

Combine an L1 in-memory cache with an L2 distributed cache to reduce latency for hot keys while maintaining cache consistency across instances.

intermediate

Type Object Pattern

Define game object types as runtime data rather than hard-coding them as classes, enabling designers to create new entity variants without recompiling the codebase.

intermediate

Unit of Work Pattern

Track changes to in-memory objects during a business transaction and commit all updates atomically to the database, ensuring consistency.

intermediate

Value Object Pattern

Model domain concepts by value rather than identity. An immutable object defined by its attributes, not by a unique ID.

advanced

Visitor Pattern

Represent an operation to be performed on elements of an object structure without changing the classes of the elements. A behavioral design pattern.

advanced

Visitor Pattern for Extensible Operations on Object

Separate algorithms from the objects they operate on, allowing new operations to be added without modifying existing element classes

advanced

Write-Behind Cache Pattern

Write to cache synchronously and persist to the database asynchronously for high-throughput write workloads with eventual consistency.

intermediate

Write-Through Cache Pattern

Synchronously write to both cache and backing store so the cache always has the latest data without TTL-based invalidation.

intermediate

Container-Presenter: Separate Data Logic from Rendering

How to separate data-fetching logic from rendering in React using the container-presenter pattern. Covers hooks migration, testing benefits, and trade-offs.

intermediate

CSS Architecture: Utility-First with Component-Scoped Layers

How to organize CSS with utility-first classes and component-scoped layers. Covers Tailwind CSS, CSS layers, BEM, CSS modules, and design tokens.

intermediate

Custom Hook Composition

How to compose reusable logic with custom React hooks. Covers hook composition patterns, dependency arrays, context integration, and testing strategies.

advanced

Islands Architecture

How to ship interactivity only where needed using islands architecture. Covers Astro islands, partial hydration, React islands, and performance benefits.

intermediate

Optimistic Update: Update UI Immediately, Reconcile on

How to update UI immediately and reconcile on server response in React. Covers rollback on error, conflict resolution, and React Query integration.

intermediate

Progressive Enhancement

How to build a functional HTML baseline and progressively enhance with JavaScript. Covers core functionality, feature detection, graceful degradation, and accessibility.

advanced

State Machine UI: Finite State Machines for UI

How to model UI state transitions with finite state machines in React. Covers XState, statecharts, guarded transitions, and preventing impossible states.

advanced

Suspense Boundary: Declarative Loading States with React

How to use React Suspense boundaries for declarative loading states. Covers data fetching, streaming SSR, nested boundaries, and error boundaries.

intermediate

GraphQL Batched Resolver Pattern

Resolve nested GraphQL fields in a single batched request to eliminate N+1 queries and reduce database load.

intermediate

GraphQL Connection Pagination Pattern

Implement Relay-style cursor-based pagination with edges, nodes, and pageInfo for stable GraphQL list queries.

intermediate

GraphQL DataLoader Pattern

Coalesce individual load requests into batched calls with per-request caching to prevent N+1 queries and redundant fetches.

intermediate

GraphQL Error Extension Pattern

Attach structured metadata to GraphQL errors using extension codes for predictable client-side error handling.

advanced

GraphQL Federated Entity Pattern

Share entity types across federated GraphQL services so the gateway can resolve fields from multiple subgraphs transparently.

advanced

GraphQL Interface Polymorphism Pattern

Model polymorphic types with GraphQL interfaces to share field contracts across different object types while keeping resolvers type-specific.

intermediate

GraphQL Mutation Validation Pattern

Centralize input validation for GraphQL mutations using custom validators, schema directives, and structured error responses.

advanced

GraphQL Schema Stitching Pattern

Merge multiple independent GraphQL schemas into a single unified schema that clients can query as one graph.

advanced

Circuit Breaker with Monitoring

How to expose circuit breaker state as metrics for observability. Covers Prometheus integration, alerting rules, dashboards, and state transitions.

intermediate

Correlation ID: Trace Requests Across Distributed Services

How to propagate correlation IDs across service boundaries for end-to-end request tracing. Covers HTTP headers, message queues, and logging integration.

advanced

Distributed Tracing: Propagate Trace Context Across Services

How to propagate trace context across service boundaries with OpenTelemetry. Covers span creation, context propagation, sampling, and trace analysis.

intermediate

Health Check Pattern: Expose Liveness and Readiness Probes

How to implement liveness and readiness probes for container orchestration. Covers Kubernetes probes, dependency checks, graceful degradation, and probe endpoints.

intermediate

Metrics Aggregation: Collect, Tag

How to collect, tag, and aggregate business metrics for observability. Covers Prometheus, OpenTelemetry, custom metrics, histograms, and dashboarding.

intermediate

Structured Logging: Emit JSON Logs with Consistent Fields

How to emit structured JSON logs with consistent fields for searchability. Covers Python structlog, Winston, Serilog, log levels, and log aggregation.

intermediate

Bulkhead Pattern: Isolate Resources to Limit Blast Radius

How to isolate resources per service to limit blast radius. Covers thread pool isolation, connection pool partitioning, semaphore-based bulkheads, and resource quotas.

advanced

Circuit Breaker Half-Open

How to test service recovery with half-open circuit breaker state transitions. Covers closed, open, half-open states, trial requests, and gradual recovery.

advanced

Fallover: Switch to Standby on Primary Failure Detection

How to switch to a standby system on primary failure detection. Covers active-passive, active-active, health monitoring, DNS fallover, database replication, and automated promotion.

intermediate

Graceful Shutdown: Drain In-Flight Requests Before Exit

How to drain in-flight requests before process exit. Covers signal handling, health check removal, connection draining, timeout enforcement, and cleanup hooks.

intermediate

Token Bucket Rate Limiter: Smooth Traffic with Token Buckets

How to implement token bucket rate limiting for API protection. Covers bucket refill, burst handling, per-key buckets, distributed rate limiting with Redis, and sliding windows.

intermediate

Retry with Jitter: Exponential Backoff and Random Jitter

How to retry failed operations with exponential backoff and random jitter. Covers full jitter, equal jitter, decorrelated jitter, retry budgets, and idempotency.

advanced

Contract Testing: Verify Consumer-Producer API Contracts

How to use contract testing to verify that API producers and consumers agree on request and response shapes. Covers Pact consumer-driven contracts and provider verification.

beginner

Fixture Setup/Teardown: Reusable Test Context Lifecycle

How to use setup and teardown fixtures to create reusable test context. Covers beforeEach, factory functions, fixture objects, and cleanup with examples.

advanced

Golden Master Testing

How to use golden master testing to characterize legacy code behavior before refactoring. Covers capturing output, comparing baselines, and incremental refactoring.

intermediate

Mock Server: Stand Up a Mock Server for Integration Test

How to use mock servers to isolate integration tests from external dependencies. Covers WireMock, nock, MSW, and Mountebank with configuration examples.

beginner

Parameterized Test: Run the Same Logic Across Multiple

How to write parameterized tests to verify the same logic across multiple inputs. Covers pytest parametrize, Jest test.each, JUnit ParameterizedTest, and data providers.

intermediate

Snapshot Testing: Capture and Compare Serialized Output

How to use snapshot testing to detect unintended changes in serialized output. Covers Jest snapshots, pytest snapshot, and inline vs external snapshots.

intermediate

Test Double: Replace Dependencies with Stubs, Spies, Fakes

How to use test doubles to isolate units under test. Covers stubs, spies, fakes, mocks, and dummy objects with examples in Python, JavaScript, and Java.

intermediate

Test Pyramid: Balance Unit, Integration

How to structure a test suite using the test pyramid. Covers unit, integration, and E2E test proportions, the testing trophy, and ice cream cone anti-pattern.