Skip to content
Plurafy

Software Architectural Pattern

An architectural pattern is a concrete, reusable solution that implements a architectural style’s vocabulary to fix a specific structural, data, or communication problem within that system.

Common Architectural Patterns

  • Inbound-Outbound Pattern: Separates the handling of incoming requests (inbound) from the processing and sending of responses (outbound), often used in messaging and integration systems.
  • Queue-Based Pattern: Uses a queue to decouple the sender and receiver of messages, allowing asynchronous communication and improving system scalability and fault tolerance.
  • Inbox/Outbox Pattern: Ensures reliable message delivery by storing messages in an inbox or outbox, typically used in distributed systems to achieve eventual consistency.
  • Backend-for-Frontend (BFF) Pattern: Introduces a dedicated backend service for each frontend, optimizing communication and data handling between the frontend and backend systems.
  • Client-Server Model: Divides the system into clients that request services and servers that provide them, enabling centralized control and resource management.
  • Model-View-Controller (MVC): Separates the application into models (data), views (UI), and controllers (business logic).
  • Batch Processing Pattern: Handles large volumes of data by processing it in batches, often used for tasks like data transformation, reporting, and ETL (Extract, Transform, Load) operations.
  • Circuit Breaker Pattern: Protects a system from cascading failures by detecting failures and temporarily halting requests to a failing component, allowing it to recover.
  • Saga Pattern: Manages long-running transactions by breaking them into a series of smaller, compensatable transactions, ensuring data consistency across distributed systems.
  • Retry Pattern: Automatically retries failed operations a specified number of times, helping to handle transient failures and improve system resilience.
  • Asynchronous Messaging Pattern: Decouples the sender and receiver of messages, allowing them to communicate asynchronously, improving system scalability and responsiveness.
  • CQRS (Command Query Responsibility Segregation) Pattern: Separates the read and write operations of a system into distinct models, allowing for optimized performance, scalability, and maintainability for each operation type.

The inbound-outbound architecture pattern, most famously known as Hexagonal Architecture or Ports and Adapters, isolates core business logic from external systems like databases, user interfaces, or third-party APIs. It achieves this by defining clear inbound and outbound ports through which the core logic interacts with the outside world, allowing for easier testing, maintenance, and adaptability to changing external systems.

Instead of letting infrastructure concerns pollute your business rules (the “layered architecture trap”), the system is divided into two distinct regions:

  • The Inside (Core): Pure business logic, domain entities, and rules that do not know or care where data comes from or where it goes.
  • The Outside (Infrastructure): Handles all external interactions, such as databases, user interfaces, messaging systems, and third-party APIs. It communicates with the core exclusively through well-defined inbound and outbound ports.
  • Inbound (Primary / Driving) Side:
    • Inbound Ports: Interfaces that define what actions can be triggered on the application (e.g., a use-case interface like PlaceOrderUseCase).
    • Inbound Adapters: Concrete implementations that translate external inputs—such as a REST controller, GraphQL API, CLI command, or message queue handler—into calls the core understands.
  • Outbound (Secondary / Driven) Side:
    • Outbound Ports: Interfaces defined by the core specifying what the core needs from the outside world (e.g., PaymentGateway or OrderRepository).
    • Outbound Adapters: Concrete implementations that fulfill those interfaces by talking to real infrastructure—such as a PostgreSQL database driver, a Stripe API client, or an SMTP mail server.

A Queue-Based Pattern (commonly implemented as Queue-Based Load Leveling) is a distributed system design pattern that uses an intermediary buffer (a message queue) to decouple task generation (producers) from task execution (consumers). This pattern helps to smooth out spikes in load, improve system resilience, and enable asynchronous processing of tasks.

  • Producers: The clients, APIs, or services that generate tasks or messages and push them onto the queue.
  • Message Queue / Broker: The temporary storage buffer (such as Amazon SQS or RabbitMQ) that holds messages until they are retrieved.
  • Consumers(Workers): The background services that pull messages from the queue and execute the actual work at a controlled, steady pace.
  • Decoupling: Producers and consumers do not need to know about each other’s state, location, or immediate availability.
  • Resilience & Availability: If a downstream service or database goes down, messages stay safely in the queue and are processed once the service recovers.
  • Independent Scaling: You can scale your web/API tier and your worker tier separately depending on where the actual bottleneck lies.
  • Smooths Out Traffic: Converts erratic, high-volume peak loads into a steady, manageable stream of background jobs.
  • Latency: Introduces asynchronous delay; the client or end-user does not get an immediate real-time result for the task.
  • Eventual Consistency: The system takes time to catch up, meaning data changes do not reflect instantaneously across all views.
  • Queue Overload & Task Starvation: If producers generate work faster than consumers can clear it, the queue size grows indefinitely unless limits, monitoring, or dead-letter queues are set up.
  • Complexity: Requires handling duplicate messages (“at-least-once” delivery), message ordering, and failure retries with exponential backoff.
  • Order Processing Systems: E-commerce platforms can use queues to handle order fulfillment asynchronously, ensuring that spikes in orders do not overwhelm the system.
  • Web-Queue-Worker Architectures: Offloading heavy background tasks like generating PDF reports, resizing uploaded images, or sending bulk emails to background workers via a queue to avoid blocking the main application flow.
  • Data Processing Pipelines: Tasks like ETL (Extract, Transform, Load) operations, video encoding, or image processing can be queued to manage load and ensure reliable processing.
  • Asynchronous Microservices Communication: Queues can facilitate asynchronous communication between microservices, improving decoupling and resilience.

The Inbox and Outbox Pattern are complementary architectural design patterns used in distributed systems and microservices to solve the “dual-write” problem and guarantee reliable message delivery and consumption.

The dual-write problem occurs in microservices when a service must update two independent, non-transactionally linked systems—such as writing to a local database and publishing an event to a message broker (like Apache Kafka)—without a single distributed transaction covering both. If one succeeds and the other fails, the systems drift into an inconsistent state (e.g., an order is saved in the database, but the crash prevents publishing the “OrderCreated” event).

Because an application cannot atomically update a database and publish/receive messages from a broker (like Kafka or RabbitMQ) in a single network call, things can fail halfway. These patterns use local database tables as reliable buffers to achieve consistency.

Ensures at-least once delivery of outgoing messages.

The Problem:

Your service updates a database (e.g., creating an order) and needs to publish an event (“OrderCreated”) to a message broker. If the app crashes right after the DB write but before publishing the event, the event is lost. If you publish first and the DB write fails, you have an orphan event.

How It Works:

  1. The application writes both the business data (e.g., Orders table) and the outgoing message (outbox table) inside the same local database transaction.
  2. A separate background process, relay worker, or Change Data Capture (CDC) tool reads unprocessed rows from the outbox table and publishes them to the message broker.
  3. Once published, the outbox record is marked as sent or deleted.

Ensures that each incoming message from the broker is processed exactly once, even if the broker delivers it multiple times.

The Problem:

Message brokers usually provide at-least-once delivery, meaning network blips or retry loops can cause the same message to be delivered to a consumer multiple times. Processing a payment or order twice causes bugs.

How It Works:

  1. When a consumer receives a message, it doesn’t immediately execute business logic.
  2. Instead, it writes the incoming message and its unique message_id into an inbox table within a local database transaction.
  3. If the message_id already exists in the inbox table (a duplicate), the system ignores it or safely acknowledges and drops it.
  4. A background worker picks up unprocessed inbox entries to run the actual business logic safely.

The circuit breaker pattern is a software design pattern used in distributed systems and microservices to detect failures and encapsulate the logic of preventing a failure from constantly recurring during maintenance, temporary outages, or network issues.

Popularized by Michael Nygard in his book Release It!, it functions similarly to an electrical circuit breaker by stopping traffic to a failing dependency so the system can recover.

A circuit breaker operates in three states:

  1. Closed:
    • Normal operation
    • Requests flow freely to the remote service.
    • The circuit counts recent failures. If the failure count exceeds a predefined threshold(e.g., 50% of requests failing within a 10-second window), it transitions to the open state.
  2. Open:
    • Fails fast immediately without attempting to call the downstream service.
    • Prevents thread exhaustion, connection pile-ups, and network congestion.
    • Often returns a default fallback response, cached data, or an explicit error message.
    • After a pre-configured timeout period expires, it transitions to the Half-Open state.
  3. Half-Open:
    • After a timeout, allows a limited number of trial/test requests to pass through to the target service.
    • If these test requests succeed, the breaker resets to Closed.
    • If any of the test requests fail, it reverts to Open and resets the timeout clock.
  • Prevents Cascading Failures: Stops a single slow or dead microservice from dragging down entire upstream calling services.
  • Fast Failure: Eliminates long wait times caused by hanging network calls or timeout thresholds.
  • Self-Recovery Time: Gives struggling databases, APIs, or external services breathing room to recover from high load or transient glitches.
  • Fallback Handling: Allows applications to gracefully degrade functionality (e.g., displaying cached product recommendations instead of crashing a checkout page).

The Saga pattern is a design pattern used to manage distributed transactions and maintain data consistency across multiple microservices without locking shared databases.

Instead of a single global ACID (Atomicity, Consistency, Isolation, Durability) transaction, a saga breaks a business process down into a sequence of local transactions. Each service updates its own database and publishes an event or message to trigger the next step.

Because local transactions commit data independently to separate databases, traditional rollbacks are impossible once a step finishes.

  • If a step fails halfway through the sequence, the saga executes a series of compensating transactions in reverse order.
  • These compensating actions undo the changes made by preceding local transactions (e.g., refunding a payment or releasing reserved inventory if order fulfillment fails).
  • The system achieves eventual consistency rather than immediate consistency.

Sagas are coordinated in one of two ways:

  1. Choreography (Decentralized):
    • Services listen to domain events and execute their local transactions without a central controller.
    • Best suited for simple workflows with a small number of participants.
    • Can become hard to track or lead to cyclic dependencies as the system grows.
  2. Orchestration (Centralized):
    • A central coordinator (the Saga Execution Coordinator or SEC) tells each participant what local transaction to execute and when.
    • The orchestrator maintains a transaction log and explicitly triggers compensations if a step fails.
    • Better for complex workflows, though the orchestrator can become a single point of failure if not designed carefully.

Asynchronous messaging is a communication pattern where services exchange messages without waiting for an immediate response. This decouples the sender and receiver, allowing them to operate independently and improving system resilience and scalability.

  • Messages are sent to a specific queue and consumed by a single receiver.
  • Ensures reliable delivery and decouples the sender and receiver in time.
  • Commonly used for task queues, background processing, and decoupled service communication.
  • Provides load-leveling and durability if the receiver goes offline.
  • Enables components to communicate through a message broker.
  • Publishers send messages to topics and subscribers receive messages from topics they are interested in, promoting decoupling and scalability.
  • The sender sends a request message and continues processing without waiting for an immediate response.
  • The receiver processes the request and sends a reply message back to the sender asynchronously on a separate channel or callback at a later time.
  • Useful for scenarios where the sender needs a response but cannot block while waiting, promoting decoupling and improving system responsiveness.
  • The sender dispatches a message without waiting for any acknowledgment or response from the receiver.
  • Useful for scenarios where the sender does not need to know the outcome of the operation, such as logging or notifications.
  • Promotes decoupling and reduces latency for the sender.

CQRS (Command Query Responsibility Segregation) is an architectural design pattern that separates the models used to read data from the models used to write or update data. Instead of forcing a single data model or database schema to handle both tasks simultaneously, which often leads to severe performance bottlenecks, CQRS splits responsibilities cleanly down the middle.

CQRS extends Bertrand Meyer’s principle of Command Query Separation (CQS) from the object level to the architecture level.

  • Commands (The Write Side):
    • The command model handles create, update, and delete operations.
    • These represent task-based operations that change the system state (e.g., AddProductToCart, SubmitPayment).
    • They focus on enforcing business rules, validating logic, and ensuring consistency.
    • Commands do not return data, only a success/failure status.
  • Queries (The Read Side):
    • The query model handles read operations.
    • These are operations that fetch data to display to users (e.g., GetProductDetails, FetchUserOrders).
    • Queries only read data, never modify it, and typically return clean, pre-mapped DTOs (Data Transfer Objects).

This separation allows for optimized read and write paths, scalability, and flexibility in handling complex business logic.

While CQRS can be implemented inside a single code base using separate classes or database tables, it is most commonly applied in distributed microservices environments using two separate databases for the read and write sides, allowing each to be optimized independently for performance, scalability, and consistency.

  1. The Client submits a command.
  2. The Command Side processes the change, applies business constraints, and commits it to the Write Database (acting as the system’s absolute source of truth)
  3. The Synchronization Layer emits a domain event (e.g., via a message broker like Kafka or RabbitMQ). An event handler captures this and asynchronously writes to the Read Database.
  4. The Client stays updated asynchronously and queries the Read Database to retrieve the updated data, ensuring that read operations are fast and optimized for the specific query patterns.
  • Independent Scaling: If an e-commerce site experiences 1,000 product searches (reads) for every 1 purchase (write), you can scale up the hardware for the Read API/Database without wasting budget on scaling the complex Write side.
  • Optimized Data Schemas: The write DB can be highly normalized to prevent data anomalies. The read DB can be denormalized (or materialized views) to avoid slow database joins, achieving extreme fetch speeds.
  • Simpler Codebases: Splitting code into dedicated Command Handlers and Query Handlers keeps components clean, unentangled, and easier to maintain.
  • Eventual Consistency: Because sync happens asynchronously via events, a user might update their profile but not see the change on screen immediately for a brief fraction of a second.
  • Architectural Complexity: Managing multiple models, message brokers, and code pathways increases system maintenance overhead.
  • No Global ACID Transactions: Splitting databases across boundaries drops full transaction guarantees across the read and write models.